fineuploader.js 338 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455
  1. // Fine Uploader 5.15.4 - MIT licensed. http://fineuploader.com
  2. (function(global) {
  3. var qq = function(element) {
  4. "use strict";
  5. return {
  6. hide: function() {
  7. element.style.display = "none";
  8. return this;
  9. },
  10. attach: function(type, fn) {
  11. if (element.addEventListener) {
  12. element.addEventListener(type, fn, false);
  13. } else if (element.attachEvent) {
  14. element.attachEvent("on" + type, fn);
  15. }
  16. return function() {
  17. qq(element).detach(type, fn);
  18. };
  19. },
  20. detach: function(type, fn) {
  21. if (element.removeEventListener) {
  22. element.removeEventListener(type, fn, false);
  23. } else if (element.attachEvent) {
  24. element.detachEvent("on" + type, fn);
  25. }
  26. return this;
  27. },
  28. contains: function(descendant) {
  29. if (!descendant) {
  30. return false;
  31. }
  32. if (element === descendant) {
  33. return true;
  34. }
  35. if (element.contains) {
  36. return element.contains(descendant);
  37. } else {
  38. return !!(descendant.compareDocumentPosition(element) & 8);
  39. }
  40. },
  41. insertBefore: function(elementB) {
  42. elementB.parentNode.insertBefore(element, elementB);
  43. return this;
  44. },
  45. remove: function() {
  46. element.parentNode.removeChild(element);
  47. return this;
  48. },
  49. css: function(styles) {
  50. if (element.style == null) {
  51. throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!");
  52. }
  53. if (styles.opacity != null) {
  54. if (typeof element.style.opacity !== "string" && typeof element.filters !== "undefined") {
  55. styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")";
  56. }
  57. }
  58. qq.extend(element.style, styles);
  59. return this;
  60. },
  61. hasClass: function(name, considerParent) {
  62. var re = new RegExp("(^| )" + name + "( |$)");
  63. return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className));
  64. },
  65. addClass: function(name) {
  66. if (!qq(element).hasClass(name)) {
  67. element.className += " " + name;
  68. }
  69. return this;
  70. },
  71. removeClass: function(name) {
  72. var re = new RegExp("(^| )" + name + "( |$)");
  73. element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, "");
  74. return this;
  75. },
  76. getByClass: function(className, first) {
  77. var candidates, result = [];
  78. if (first && element.querySelector) {
  79. return element.querySelector("." + className);
  80. } else if (element.querySelectorAll) {
  81. return element.querySelectorAll("." + className);
  82. }
  83. candidates = element.getElementsByTagName("*");
  84. qq.each(candidates, function(idx, val) {
  85. if (qq(val).hasClass(className)) {
  86. result.push(val);
  87. }
  88. });
  89. return first ? result[0] : result;
  90. },
  91. getFirstByClass: function(className) {
  92. return qq(element).getByClass(className, true);
  93. },
  94. children: function() {
  95. var children = [], child = element.firstChild;
  96. while (child) {
  97. if (child.nodeType === 1) {
  98. children.push(child);
  99. }
  100. child = child.nextSibling;
  101. }
  102. return children;
  103. },
  104. setText: function(text) {
  105. element.innerText = text;
  106. element.textContent = text;
  107. return this;
  108. },
  109. clearText: function() {
  110. return qq(element).setText("");
  111. },
  112. hasAttribute: function(attrName) {
  113. var attrVal;
  114. if (element.hasAttribute) {
  115. if (!element.hasAttribute(attrName)) {
  116. return false;
  117. }
  118. return /^false$/i.exec(element.getAttribute(attrName)) == null;
  119. } else {
  120. attrVal = element[attrName];
  121. if (attrVal === undefined) {
  122. return false;
  123. }
  124. return /^false$/i.exec(attrVal) == null;
  125. }
  126. }
  127. };
  128. };
  129. (function() {
  130. "use strict";
  131. qq.canvasToBlob = function(canvas, mime, quality) {
  132. return qq.dataUriToBlob(canvas.toDataURL(mime, quality));
  133. };
  134. qq.dataUriToBlob = function(dataUri) {
  135. var arrayBuffer, byteString, createBlob = function(data, mime) {
  136. var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
  137. if (blobBuilder) {
  138. blobBuilder.append(data);
  139. return blobBuilder.getBlob(mime);
  140. } else {
  141. return new Blob([ data ], {
  142. type: mime
  143. });
  144. }
  145. }, intArray, mimeString;
  146. if (dataUri.split(",")[0].indexOf("base64") >= 0) {
  147. byteString = atob(dataUri.split(",")[1]);
  148. } else {
  149. byteString = decodeURI(dataUri.split(",")[1]);
  150. }
  151. mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
  152. arrayBuffer = new ArrayBuffer(byteString.length);
  153. intArray = new Uint8Array(arrayBuffer);
  154. qq.each(byteString, function(idx, character) {
  155. intArray[idx] = character.charCodeAt(0);
  156. });
  157. return createBlob(arrayBuffer, mimeString);
  158. };
  159. qq.log = function(message, level) {
  160. if (window.console) {
  161. if (!level || level === "info") {
  162. window.console.log(message);
  163. } else {
  164. if (window.console[level]) {
  165. window.console[level](message);
  166. } else {
  167. window.console.log("<" + level + "> " + message);
  168. }
  169. }
  170. }
  171. };
  172. qq.isObject = function(variable) {
  173. return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]";
  174. };
  175. qq.isFunction = function(variable) {
  176. return typeof variable === "function";
  177. };
  178. qq.isArray = function(value) {
  179. return Object.prototype.toString.call(value) === "[object Array]" || value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer;
  180. };
  181. qq.isItemList = function(maybeItemList) {
  182. return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]";
  183. };
  184. qq.isNodeList = function(maybeNodeList) {
  185. return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || maybeNodeList.item && maybeNodeList.namedItem;
  186. };
  187. qq.isString = function(maybeString) {
  188. return Object.prototype.toString.call(maybeString) === "[object String]";
  189. };
  190. qq.trimStr = function(string) {
  191. if (String.prototype.trim) {
  192. return string.trim();
  193. }
  194. return string.replace(/^\s+|\s+$/g, "");
  195. };
  196. qq.format = function(str) {
  197. var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}");
  198. qq.each(args, function(idx, val) {
  199. var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace + 2);
  200. newStr = strBefore + val + strAfter;
  201. nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length);
  202. if (nextIdxToReplace < 0) {
  203. return false;
  204. }
  205. });
  206. return newStr;
  207. };
  208. qq.isFile = function(maybeFile) {
  209. return window.File && Object.prototype.toString.call(maybeFile) === "[object File]";
  210. };
  211. qq.isFileList = function(maybeFileList) {
  212. return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]";
  213. };
  214. qq.isFileOrInput = function(maybeFileOrInput) {
  215. return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);
  216. };
  217. qq.isInput = function(maybeInput, notFile) {
  218. var evaluateType = function(type) {
  219. var normalizedType = type.toLowerCase();
  220. if (notFile) {
  221. return normalizedType !== "file";
  222. }
  223. return normalizedType === "file";
  224. };
  225. if (window.HTMLInputElement) {
  226. if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") {
  227. if (maybeInput.type && evaluateType(maybeInput.type)) {
  228. return true;
  229. }
  230. }
  231. }
  232. if (maybeInput.tagName) {
  233. if (maybeInput.tagName.toLowerCase() === "input") {
  234. if (maybeInput.type && evaluateType(maybeInput.type)) {
  235. return true;
  236. }
  237. }
  238. }
  239. return false;
  240. };
  241. qq.isBlob = function(maybeBlob) {
  242. if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") {
  243. return true;
  244. }
  245. };
  246. qq.isXhrUploadSupported = function() {
  247. var input = document.createElement("input");
  248. input.type = "file";
  249. return input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof qq.createXhrInstance().upload !== "undefined";
  250. };
  251. qq.createXhrInstance = function() {
  252. if (window.XMLHttpRequest) {
  253. return new XMLHttpRequest();
  254. }
  255. try {
  256. return new ActiveXObject("MSXML2.XMLHTTP.3.0");
  257. } catch (error) {
  258. qq.log("Neither XHR or ActiveX are supported!", "error");
  259. return null;
  260. }
  261. };
  262. qq.isFolderDropSupported = function(dataTransfer) {
  263. return dataTransfer.items && dataTransfer.items.length > 0 && dataTransfer.items[0].webkitGetAsEntry;
  264. };
  265. qq.isFileChunkingSupported = function() {
  266. return !qq.androidStock() && qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);
  267. };
  268. qq.sliceBlob = function(fileOrBlob, start, end) {
  269. var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice;
  270. return slicer.call(fileOrBlob, start, end);
  271. };
  272. qq.arrayBufferToHex = function(buffer) {
  273. var bytesAsHex = "", bytes = new Uint8Array(buffer);
  274. qq.each(bytes, function(idx, byt) {
  275. var byteAsHexStr = byt.toString(16);
  276. if (byteAsHexStr.length < 2) {
  277. byteAsHexStr = "0" + byteAsHexStr;
  278. }
  279. bytesAsHex += byteAsHexStr;
  280. });
  281. return bytesAsHex;
  282. };
  283. qq.readBlobToHex = function(blob, startOffset, length) {
  284. var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise();
  285. fileReader.onload = function() {
  286. promise.success(qq.arrayBufferToHex(fileReader.result));
  287. };
  288. fileReader.onerror = promise.failure;
  289. fileReader.readAsArrayBuffer(initialBlob);
  290. return promise;
  291. };
  292. qq.extend = function(first, second, extendNested) {
  293. qq.each(second, function(prop, val) {
  294. if (extendNested && qq.isObject(val)) {
  295. if (first[prop] === undefined) {
  296. first[prop] = {};
  297. }
  298. qq.extend(first[prop], val, true);
  299. } else {
  300. first[prop] = val;
  301. }
  302. });
  303. return first;
  304. };
  305. qq.override = function(target, sourceFn) {
  306. var super_ = {}, source = sourceFn(super_);
  307. qq.each(source, function(srcPropName, srcPropVal) {
  308. if (target[srcPropName] !== undefined) {
  309. super_[srcPropName] = target[srcPropName];
  310. }
  311. target[srcPropName] = srcPropVal;
  312. });
  313. return target;
  314. };
  315. qq.indexOf = function(arr, elt, from) {
  316. if (arr.indexOf) {
  317. return arr.indexOf(elt, from);
  318. }
  319. from = from || 0;
  320. var len = arr.length;
  321. if (from < 0) {
  322. from += len;
  323. }
  324. for (;from < len; from += 1) {
  325. if (arr.hasOwnProperty(from) && arr[from] === elt) {
  326. return from;
  327. }
  328. }
  329. return -1;
  330. };
  331. qq.getUniqueId = function() {
  332. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
  333. var r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
  334. return v.toString(16);
  335. });
  336. };
  337. qq.ie = function() {
  338. return navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1;
  339. };
  340. qq.ie7 = function() {
  341. return navigator.userAgent.indexOf("MSIE 7") !== -1;
  342. };
  343. qq.ie8 = function() {
  344. return navigator.userAgent.indexOf("MSIE 8") !== -1;
  345. };
  346. qq.ie10 = function() {
  347. return navigator.userAgent.indexOf("MSIE 10") !== -1;
  348. };
  349. qq.ie11 = function() {
  350. return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1;
  351. };
  352. qq.edge = function() {
  353. return navigator.userAgent.indexOf("Edge") >= 0;
  354. };
  355. qq.safari = function() {
  356. return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
  357. };
  358. qq.chrome = function() {
  359. return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1;
  360. };
  361. qq.opera = function() {
  362. return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1;
  363. };
  364. qq.firefox = function() {
  365. return !qq.edge() && !qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === "";
  366. };
  367. qq.windows = function() {
  368. return navigator.platform === "Win32";
  369. };
  370. qq.android = function() {
  371. return navigator.userAgent.toLowerCase().indexOf("android") !== -1;
  372. };
  373. qq.androidStock = function() {
  374. return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0;
  375. };
  376. qq.ios6 = function() {
  377. return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1;
  378. };
  379. qq.ios7 = function() {
  380. return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1;
  381. };
  382. qq.ios8 = function() {
  383. return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1;
  384. };
  385. qq.ios800 = function() {
  386. return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1;
  387. };
  388. qq.ios = function() {
  389. return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1;
  390. };
  391. qq.iosChrome = function() {
  392. return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1;
  393. };
  394. qq.iosSafari = function() {
  395. return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1;
  396. };
  397. qq.iosSafariWebView = function() {
  398. return qq.ios() && !qq.iosChrome() && !qq.iosSafari();
  399. };
  400. qq.preventDefault = function(e) {
  401. if (e.preventDefault) {
  402. e.preventDefault();
  403. } else {
  404. e.returnValue = false;
  405. }
  406. };
  407. qq.toElement = function() {
  408. var div = document.createElement("div");
  409. return function(html) {
  410. div.innerHTML = html;
  411. var element = div.firstChild;
  412. div.removeChild(element);
  413. return element;
  414. };
  415. }();
  416. qq.each = function(iterableItem, callback) {
  417. var keyOrIndex, retVal;
  418. if (iterableItem) {
  419. if (window.Storage && iterableItem.constructor === window.Storage) {
  420. for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
  421. retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex)));
  422. if (retVal === false) {
  423. break;
  424. }
  425. }
  426. } else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) {
  427. for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
  428. retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
  429. if (retVal === false) {
  430. break;
  431. }
  432. }
  433. } else if (qq.isString(iterableItem)) {
  434. for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
  435. retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex));
  436. if (retVal === false) {
  437. break;
  438. }
  439. }
  440. } else {
  441. for (keyOrIndex in iterableItem) {
  442. if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) {
  443. retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
  444. if (retVal === false) {
  445. break;
  446. }
  447. }
  448. }
  449. }
  450. }
  451. };
  452. qq.bind = function(oldFunc, context) {
  453. if (qq.isFunction(oldFunc)) {
  454. var args = Array.prototype.slice.call(arguments, 2);
  455. return function() {
  456. var newArgs = qq.extend([], args);
  457. if (arguments.length) {
  458. newArgs = newArgs.concat(Array.prototype.slice.call(arguments));
  459. }
  460. return oldFunc.apply(context, newArgs);
  461. };
  462. }
  463. throw new Error("first parameter must be a function!");
  464. };
  465. qq.obj2url = function(obj, temp, prefixDone) {
  466. var uristrings = [], prefix = "&", add = function(nextObj, i) {
  467. var nextTemp = temp ? /\[\]$/.test(temp) ? temp : temp + "[" + i + "]" : i;
  468. if (nextTemp !== "undefined" && i !== "undefined") {
  469. uristrings.push(typeof nextObj === "object" ? qq.obj2url(nextObj, nextTemp, true) : Object.prototype.toString.call(nextObj) === "[object Function]" ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj));
  470. }
  471. };
  472. if (!prefixDone && temp) {
  473. prefix = /\?/.test(temp) ? /\?$/.test(temp) ? "" : "&" : "?";
  474. uristrings.push(temp);
  475. uristrings.push(qq.obj2url(obj));
  476. } else if (Object.prototype.toString.call(obj) === "[object Array]" && typeof obj !== "undefined") {
  477. qq.each(obj, function(idx, val) {
  478. add(val, idx);
  479. });
  480. } else if (typeof obj !== "undefined" && obj !== null && typeof obj === "object") {
  481. qq.each(obj, function(prop, val) {
  482. add(val, prop);
  483. });
  484. } else {
  485. uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj));
  486. }
  487. if (temp) {
  488. return uristrings.join(prefix);
  489. } else {
  490. return uristrings.join(prefix).replace(/^&/, "").replace(/%20/g, "+");
  491. }
  492. };
  493. qq.obj2FormData = function(obj, formData, arrayKeyName) {
  494. if (!formData) {
  495. formData = new FormData();
  496. }
  497. qq.each(obj, function(key, val) {
  498. key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key;
  499. if (qq.isObject(val)) {
  500. qq.obj2FormData(val, formData, key);
  501. } else if (qq.isFunction(val)) {
  502. formData.append(key, val());
  503. } else {
  504. formData.append(key, val);
  505. }
  506. });
  507. return formData;
  508. };
  509. qq.obj2Inputs = function(obj, form) {
  510. var input;
  511. if (!form) {
  512. form = document.createElement("form");
  513. }
  514. qq.obj2FormData(obj, {
  515. append: function(key, val) {
  516. input = document.createElement("input");
  517. input.setAttribute("name", key);
  518. input.setAttribute("value", val);
  519. form.appendChild(input);
  520. }
  521. });
  522. return form;
  523. };
  524. qq.parseJson = function(json) {
  525. if (window.JSON && qq.isFunction(JSON.parse)) {
  526. return JSON.parse(json);
  527. } else {
  528. return eval("(" + json + ")");
  529. }
  530. };
  531. qq.getExtension = function(filename) {
  532. var extIdx = filename.lastIndexOf(".") + 1;
  533. if (extIdx > 0) {
  534. return filename.substr(extIdx, filename.length - extIdx);
  535. }
  536. };
  537. qq.getFilename = function(blobOrFileInput) {
  538. if (qq.isInput(blobOrFileInput)) {
  539. return blobOrFileInput.value.replace(/.*(\/|\\)/, "");
  540. } else if (qq.isFile(blobOrFileInput)) {
  541. if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) {
  542. return blobOrFileInput.fileName;
  543. }
  544. }
  545. return blobOrFileInput.name;
  546. };
  547. qq.DisposeSupport = function() {
  548. var disposers = [];
  549. return {
  550. dispose: function() {
  551. var disposer;
  552. do {
  553. disposer = disposers.shift();
  554. if (disposer) {
  555. disposer();
  556. }
  557. } while (disposer);
  558. },
  559. attach: function() {
  560. var args = arguments;
  561. this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
  562. },
  563. addDisposer: function(disposeFunction) {
  564. disposers.push(disposeFunction);
  565. }
  566. };
  567. };
  568. })();
  569. (function() {
  570. "use strict";
  571. if (typeof define === "function" && define.amd) {
  572. define(function() {
  573. return qq;
  574. });
  575. } else if (typeof module !== "undefined" && module.exports) {
  576. module.exports = qq;
  577. } else {
  578. global.qq = qq;
  579. }
  580. })();
  581. (function() {
  582. "use strict";
  583. qq.Error = function(message) {
  584. this.message = "[Fine Uploader " + qq.version + "] " + message;
  585. };
  586. qq.Error.prototype = new Error();
  587. })();
  588. qq.version = "5.15.4";
  589. qq.supportedFeatures = function() {
  590. "use strict";
  591. var supportsUploading, supportsUploadingBlobs, supportsFileDrop, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews, supportsUploadProgress;
  592. function testSupportsFileInputElement() {
  593. var supported = true, tempInput;
  594. try {
  595. tempInput = document.createElement("input");
  596. tempInput.type = "file";
  597. qq(tempInput).hide();
  598. if (tempInput.disabled) {
  599. supported = false;
  600. }
  601. } catch (ex) {
  602. supported = false;
  603. }
  604. return supported;
  605. }
  606. function isChrome21OrHigher() {
  607. return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined;
  608. }
  609. function isChrome14OrHigher() {
  610. return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
  611. }
  612. function isCrossOriginXhrSupported() {
  613. if (window.XMLHttpRequest) {
  614. var xhr = qq.createXhrInstance();
  615. return xhr.withCredentials !== undefined;
  616. }
  617. return false;
  618. }
  619. function isXdrSupported() {
  620. return window.XDomainRequest !== undefined;
  621. }
  622. function isCrossOriginAjaxSupported() {
  623. if (isCrossOriginXhrSupported()) {
  624. return true;
  625. }
  626. return isXdrSupported();
  627. }
  628. function isFolderSelectionSupported() {
  629. return document.createElement("input").webkitdirectory !== undefined;
  630. }
  631. function isLocalStorageSupported() {
  632. try {
  633. return !!window.localStorage && qq.isFunction(window.localStorage.setItem);
  634. } catch (error) {
  635. return false;
  636. }
  637. }
  638. function isDragAndDropSupported() {
  639. var span = document.createElement("span");
  640. return ("draggable" in span || "ondragstart" in span && "ondrop" in span) && !qq.android() && !qq.ios();
  641. }
  642. supportsUploading = testSupportsFileInputElement();
  643. supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();
  644. supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock();
  645. supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported();
  646. supportsFolderDrop = supportsFileDrop && isChrome21OrHigher();
  647. supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();
  648. supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported();
  649. supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();
  650. supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);
  651. supportsDeleteFileCorsXhr = isCrossOriginXhrSupported();
  652. supportsDeleteFileXdr = isXdrSupported();
  653. supportsDeleteFileCors = isCrossOriginAjaxSupported();
  654. supportsFolderSelection = isFolderSelectionSupported();
  655. supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined;
  656. supportsUploadProgress = function() {
  657. if (supportsAjaxFileUploading) {
  658. return !qq.androidStock() && !qq.iosChrome();
  659. }
  660. return false;
  661. }();
  662. return {
  663. ajaxUploading: supportsAjaxFileUploading,
  664. blobUploading: supportsUploadingBlobs,
  665. canDetermineSize: supportsAjaxFileUploading,
  666. chunking: supportsChunking,
  667. deleteFileCors: supportsDeleteFileCors,
  668. deleteFileCorsXdr: supportsDeleteFileXdr,
  669. deleteFileCorsXhr: supportsDeleteFileCorsXhr,
  670. dialogElement: !!window.HTMLDialogElement,
  671. fileDrop: supportsFileDrop,
  672. folderDrop: supportsFolderDrop,
  673. folderSelection: supportsFolderSelection,
  674. imagePreviews: supportsImagePreviews,
  675. imageValidation: supportsImagePreviews,
  676. itemSizeValidation: supportsAjaxFileUploading,
  677. pause: supportsChunking,
  678. progressBar: supportsUploadProgress,
  679. resume: supportsResume,
  680. scaling: supportsImagePreviews && supportsUploadingBlobs,
  681. tiffPreviews: qq.safari(),
  682. unlimitedScaledImageSize: !qq.ios(),
  683. uploading: supportsUploading,
  684. uploadCors: supportsUploadCors,
  685. uploadCustomHeaders: supportsAjaxFileUploading,
  686. uploadNonMultipart: supportsAjaxFileUploading,
  687. uploadViaPaste: supportsUploadViaPaste
  688. };
  689. }();
  690. qq.isGenericPromise = function(maybePromise) {
  691. "use strict";
  692. return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then));
  693. };
  694. qq.Promise = function() {
  695. "use strict";
  696. var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0;
  697. qq.extend(this, {
  698. then: function(onSuccess, onFailure) {
  699. if (state === 0) {
  700. if (onSuccess) {
  701. successCallbacks.push(onSuccess);
  702. }
  703. if (onFailure) {
  704. failureCallbacks.push(onFailure);
  705. }
  706. } else if (state === -1) {
  707. onFailure && onFailure.apply(null, failureArgs);
  708. } else if (onSuccess) {
  709. onSuccess.apply(null, successArgs);
  710. }
  711. return this;
  712. },
  713. done: function(callback) {
  714. if (state === 0) {
  715. doneCallbacks.push(callback);
  716. } else {
  717. callback.apply(null, failureArgs === undefined ? successArgs : failureArgs);
  718. }
  719. return this;
  720. },
  721. success: function() {
  722. state = 1;
  723. successArgs = arguments;
  724. if (successCallbacks.length) {
  725. qq.each(successCallbacks, function(idx, callback) {
  726. callback.apply(null, successArgs);
  727. });
  728. }
  729. if (doneCallbacks.length) {
  730. qq.each(doneCallbacks, function(idx, callback) {
  731. callback.apply(null, successArgs);
  732. });
  733. }
  734. return this;
  735. },
  736. failure: function() {
  737. state = -1;
  738. failureArgs = arguments;
  739. if (failureCallbacks.length) {
  740. qq.each(failureCallbacks, function(idx, callback) {
  741. callback.apply(null, failureArgs);
  742. });
  743. }
  744. if (doneCallbacks.length) {
  745. qq.each(doneCallbacks, function(idx, callback) {
  746. callback.apply(null, failureArgs);
  747. });
  748. }
  749. return this;
  750. }
  751. });
  752. };
  753. qq.BlobProxy = function(referenceBlob, onCreate) {
  754. "use strict";
  755. qq.extend(this, {
  756. referenceBlob: referenceBlob,
  757. create: function() {
  758. return onCreate(referenceBlob);
  759. }
  760. });
  761. };
  762. qq.UploadButton = function(o) {
  763. "use strict";
  764. var self = this, disposeSupport = new qq.DisposeSupport(), options = {
  765. acceptFiles: null,
  766. element: null,
  767. focusClass: "qq-upload-button-focus",
  768. folders: false,
  769. hoverClass: "qq-upload-button-hover",
  770. ios8BrowserCrashWorkaround: false,
  771. multiple: false,
  772. name: "qqfile",
  773. onChange: function(input) {},
  774. title: null
  775. }, input, buttonId;
  776. qq.extend(options, o);
  777. buttonId = qq.getUniqueId();
  778. function createInput() {
  779. var input = document.createElement("input");
  780. input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId);
  781. input.setAttribute("title", options.title);
  782. self.setMultiple(options.multiple, input);
  783. if (options.folders && qq.supportedFeatures.folderSelection) {
  784. input.setAttribute("webkitdirectory", "");
  785. }
  786. if (options.acceptFiles) {
  787. input.setAttribute("accept", options.acceptFiles);
  788. }
  789. input.setAttribute("type", "file");
  790. input.setAttribute("name", options.name);
  791. qq(input).css({
  792. position: "absolute",
  793. right: 0,
  794. top: 0,
  795. fontFamily: "Arial",
  796. fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px",
  797. margin: 0,
  798. padding: 0,
  799. cursor: "pointer",
  800. opacity: 0
  801. });
  802. !qq.ie7() && qq(input).css({
  803. height: "100%"
  804. });
  805. options.element.appendChild(input);
  806. disposeSupport.attach(input, "change", function() {
  807. options.onChange(input);
  808. });
  809. disposeSupport.attach(input, "mouseover", function() {
  810. qq(options.element).addClass(options.hoverClass);
  811. });
  812. disposeSupport.attach(input, "mouseout", function() {
  813. qq(options.element).removeClass(options.hoverClass);
  814. });
  815. disposeSupport.attach(input, "focus", function() {
  816. qq(options.element).addClass(options.focusClass);
  817. });
  818. disposeSupport.attach(input, "blur", function() {
  819. qq(options.element).removeClass(options.focusClass);
  820. });
  821. return input;
  822. }
  823. qq(options.element).css({
  824. position: "relative",
  825. overflow: "hidden",
  826. direction: "ltr"
  827. });
  828. qq.extend(this, {
  829. getInput: function() {
  830. return input;
  831. },
  832. getButtonId: function() {
  833. return buttonId;
  834. },
  835. setMultiple: function(isMultiple, optInput) {
  836. var input = optInput || this.getInput();
  837. if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) {
  838. input.setAttribute("multiple", "");
  839. } else {
  840. if (isMultiple) {
  841. input.setAttribute("multiple", "");
  842. } else {
  843. input.removeAttribute("multiple");
  844. }
  845. }
  846. },
  847. setAcceptFiles: function(acceptFiles) {
  848. if (acceptFiles !== options.acceptFiles) {
  849. input.setAttribute("accept", acceptFiles);
  850. }
  851. },
  852. reset: function() {
  853. if (input.parentNode) {
  854. qq(input).remove();
  855. }
  856. qq(options.element).removeClass(options.focusClass);
  857. input = null;
  858. input = createInput();
  859. }
  860. });
  861. input = createInput();
  862. };
  863. qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id";
  864. qq.UploadData = function(uploaderProxy) {
  865. "use strict";
  866. var data = [], byUuid = {}, byStatus = {}, byProxyGroupId = {}, byBatchId = {};
  867. function getDataByIds(idOrIds) {
  868. if (qq.isArray(idOrIds)) {
  869. var entries = [];
  870. qq.each(idOrIds, function(idx, id) {
  871. entries.push(data[id]);
  872. });
  873. return entries;
  874. }
  875. return data[idOrIds];
  876. }
  877. function getDataByUuids(uuids) {
  878. if (qq.isArray(uuids)) {
  879. var entries = [];
  880. qq.each(uuids, function(idx, uuid) {
  881. entries.push(data[byUuid[uuid]]);
  882. });
  883. return entries;
  884. }
  885. return data[byUuid[uuids]];
  886. }
  887. function getDataByStatus(status) {
  888. var statusResults = [], statuses = [].concat(status);
  889. qq.each(statuses, function(index, statusEnum) {
  890. var statusResultIndexes = byStatus[statusEnum];
  891. if (statusResultIndexes !== undefined) {
  892. qq.each(statusResultIndexes, function(i, dataIndex) {
  893. statusResults.push(data[dataIndex]);
  894. });
  895. }
  896. });
  897. return statusResults;
  898. }
  899. qq.extend(this, {
  900. addFile: function(spec) {
  901. var status = spec.status || qq.status.SUBMITTING, id = data.push({
  902. name: spec.name,
  903. originalName: spec.name,
  904. uuid: spec.uuid,
  905. size: spec.size == null ? -1 : spec.size,
  906. status: status
  907. }) - 1;
  908. if (spec.batchId) {
  909. data[id].batchId = spec.batchId;
  910. if (byBatchId[spec.batchId] === undefined) {
  911. byBatchId[spec.batchId] = [];
  912. }
  913. byBatchId[spec.batchId].push(id);
  914. }
  915. if (spec.proxyGroupId) {
  916. data[id].proxyGroupId = spec.proxyGroupId;
  917. if (byProxyGroupId[spec.proxyGroupId] === undefined) {
  918. byProxyGroupId[spec.proxyGroupId] = [];
  919. }
  920. byProxyGroupId[spec.proxyGroupId].push(id);
  921. }
  922. data[id].id = id;
  923. byUuid[spec.uuid] = id;
  924. if (byStatus[status] === undefined) {
  925. byStatus[status] = [];
  926. }
  927. byStatus[status].push(id);
  928. spec.onBeforeStatusChange && spec.onBeforeStatusChange(id);
  929. uploaderProxy.onStatusChange(id, null, status);
  930. return id;
  931. },
  932. retrieve: function(optionalFilter) {
  933. if (qq.isObject(optionalFilter) && data.length) {
  934. if (optionalFilter.id !== undefined) {
  935. return getDataByIds(optionalFilter.id);
  936. } else if (optionalFilter.uuid !== undefined) {
  937. return getDataByUuids(optionalFilter.uuid);
  938. } else if (optionalFilter.status) {
  939. return getDataByStatus(optionalFilter.status);
  940. }
  941. } else {
  942. return qq.extend([], data, true);
  943. }
  944. },
  945. reset: function() {
  946. data = [];
  947. byUuid = {};
  948. byStatus = {};
  949. byBatchId = {};
  950. },
  951. setStatus: function(id, newStatus) {
  952. var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id);
  953. byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);
  954. data[id].status = newStatus;
  955. if (byStatus[newStatus] === undefined) {
  956. byStatus[newStatus] = [];
  957. }
  958. byStatus[newStatus].push(id);
  959. uploaderProxy.onStatusChange(id, oldStatus, newStatus);
  960. },
  961. uuidChanged: function(id, newUuid) {
  962. var oldUuid = data[id].uuid;
  963. data[id].uuid = newUuid;
  964. byUuid[newUuid] = id;
  965. delete byUuid[oldUuid];
  966. },
  967. updateName: function(id, newName) {
  968. data[id].name = newName;
  969. },
  970. updateSize: function(id, newSize) {
  971. data[id].size = newSize;
  972. },
  973. setParentId: function(targetId, parentId) {
  974. data[targetId].parentId = parentId;
  975. },
  976. getIdsInProxyGroup: function(id) {
  977. var proxyGroupId = data[id].proxyGroupId;
  978. if (proxyGroupId) {
  979. return byProxyGroupId[proxyGroupId];
  980. }
  981. return [];
  982. },
  983. getIdsInBatch: function(id) {
  984. var batchId = data[id].batchId;
  985. return byBatchId[batchId];
  986. }
  987. });
  988. };
  989. qq.status = {
  990. SUBMITTING: "submitting",
  991. SUBMITTED: "submitted",
  992. REJECTED: "rejected",
  993. QUEUED: "queued",
  994. CANCELED: "canceled",
  995. PAUSED: "paused",
  996. UPLOADING: "uploading",
  997. UPLOAD_RETRYING: "retrying upload",
  998. UPLOAD_SUCCESSFUL: "upload successful",
  999. UPLOAD_FAILED: "upload failed",
  1000. DELETE_FAILED: "delete failed",
  1001. DELETING: "deleting",
  1002. DELETED: "deleted"
  1003. };
  1004. (function() {
  1005. "use strict";
  1006. qq.basePublicApi = {
  1007. addBlobs: function(blobDataOrArray, params, endpoint) {
  1008. this.addFiles(blobDataOrArray, params, endpoint);
  1009. },
  1010. addInitialFiles: function(cannedFileList) {
  1011. var self = this;
  1012. qq.each(cannedFileList, function(index, cannedFile) {
  1013. self._addCannedFile(cannedFile);
  1014. });
  1015. },
  1016. addFiles: function(data, params, endpoint) {
  1017. this._maybeHandleIos8SafariWorkaround();
  1018. var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId, processBlob = qq.bind(function(blob) {
  1019. this._handleNewFile({
  1020. blob: blob,
  1021. name: this._options.blobs.defaultName
  1022. }, batchId, verifiedFiles);
  1023. }, this), processBlobData = qq.bind(function(blobData) {
  1024. this._handleNewFile(blobData, batchId, verifiedFiles);
  1025. }, this), processCanvas = qq.bind(function(canvas) {
  1026. var blob = qq.canvasToBlob(canvas);
  1027. this._handleNewFile({
  1028. blob: blob,
  1029. name: this._options.blobs.defaultName + ".png"
  1030. }, batchId, verifiedFiles);
  1031. }, this), processCanvasData = qq.bind(function(canvasData) {
  1032. var normalizedQuality = canvasData.quality && canvasData.quality / 100, blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);
  1033. this._handleNewFile({
  1034. blob: blob,
  1035. name: canvasData.name
  1036. }, batchId, verifiedFiles);
  1037. }, this), processFileOrInput = qq.bind(function(fileOrInput) {
  1038. if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
  1039. var files = Array.prototype.slice.call(fileOrInput.files), self = this;
  1040. qq.each(files, function(idx, file) {
  1041. self._handleNewFile(file, batchId, verifiedFiles);
  1042. });
  1043. } else {
  1044. this._handleNewFile(fileOrInput, batchId, verifiedFiles);
  1045. }
  1046. }, this), normalizeData = function() {
  1047. if (qq.isFileList(data)) {
  1048. data = Array.prototype.slice.call(data);
  1049. }
  1050. data = [].concat(data);
  1051. }, self = this, verifiedFiles = [];
  1052. this._currentBatchId = batchId;
  1053. if (data) {
  1054. normalizeData();
  1055. qq.each(data, function(idx, fileContainer) {
  1056. if (qq.isFileOrInput(fileContainer)) {
  1057. processFileOrInput(fileContainer);
  1058. } else if (qq.isBlob(fileContainer)) {
  1059. processBlob(fileContainer);
  1060. } else if (qq.isObject(fileContainer)) {
  1061. if (fileContainer.blob && fileContainer.name) {
  1062. processBlobData(fileContainer);
  1063. } else if (fileContainer.canvas && fileContainer.name) {
  1064. processCanvasData(fileContainer);
  1065. }
  1066. } else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") {
  1067. processCanvas(fileContainer);
  1068. } else {
  1069. self.log(fileContainer + " is not a valid file container! Ignoring!", "warn");
  1070. }
  1071. });
  1072. this.log("Received " + verifiedFiles.length + " files.");
  1073. this._prepareItemsForUpload(verifiedFiles, params, endpoint);
  1074. }
  1075. },
  1076. cancel: function(id) {
  1077. this._handler.cancel(id);
  1078. },
  1079. cancelAll: function() {
  1080. var storedIdsCopy = [], self = this;
  1081. qq.extend(storedIdsCopy, this._storedIds);
  1082. qq.each(storedIdsCopy, function(idx, storedFileId) {
  1083. self.cancel(storedFileId);
  1084. });
  1085. this._handler.cancelAll();
  1086. },
  1087. clearStoredFiles: function() {
  1088. this._storedIds = [];
  1089. },
  1090. continueUpload: function(id) {
  1091. var uploadData = this._uploadData.retrieve({
  1092. id: id
  1093. });
  1094. if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
  1095. return false;
  1096. }
  1097. if (uploadData.status === qq.status.PAUSED) {
  1098. this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id)));
  1099. this._uploadFile(id);
  1100. return true;
  1101. } else {
  1102. this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error");
  1103. }
  1104. return false;
  1105. },
  1106. deleteFile: function(id) {
  1107. return this._onSubmitDelete(id);
  1108. },
  1109. doesExist: function(fileOrBlobId) {
  1110. return this._handler.isValid(fileOrBlobId);
  1111. },
  1112. drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
  1113. var promiseToReturn = new qq.Promise(), fileOrUrl, options;
  1114. if (this._imageGenerator) {
  1115. fileOrUrl = this._thumbnailUrls[fileId];
  1116. options = {
  1117. customResizeFunction: customResizeFunction,
  1118. maxSize: maxSize > 0 ? maxSize : null,
  1119. scale: maxSize > 0
  1120. };
  1121. if (!fromServer && qq.supportedFeatures.imagePreviews) {
  1122. fileOrUrl = this.getFile(fileId);
  1123. }
  1124. if (fileOrUrl == null) {
  1125. promiseToReturn.failure({
  1126. container: imgOrCanvas,
  1127. error: "File or URL not found."
  1128. });
  1129. } else {
  1130. this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(function success(modifiedContainer) {
  1131. promiseToReturn.success(modifiedContainer);
  1132. }, function failure(container, reason) {
  1133. promiseToReturn.failure({
  1134. container: container,
  1135. error: reason || "Problem generating thumbnail"
  1136. });
  1137. });
  1138. }
  1139. } else {
  1140. promiseToReturn.failure({
  1141. container: imgOrCanvas,
  1142. error: "Missing image generator module"
  1143. });
  1144. }
  1145. return promiseToReturn;
  1146. },
  1147. getButton: function(fileId) {
  1148. return this._getButton(this._buttonIdsForFileIds[fileId]);
  1149. },
  1150. getEndpoint: function(fileId) {
  1151. return this._endpointStore.get(fileId);
  1152. },
  1153. getFile: function(fileOrBlobId) {
  1154. return this._handler.getFile(fileOrBlobId) || null;
  1155. },
  1156. getInProgress: function() {
  1157. return this._uploadData.retrieve({
  1158. status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ]
  1159. }).length;
  1160. },
  1161. getName: function(id) {
  1162. return this._uploadData.retrieve({
  1163. id: id
  1164. }).name;
  1165. },
  1166. getParentId: function(id) {
  1167. var uploadDataEntry = this.getUploads({
  1168. id: id
  1169. }), parentId = null;
  1170. if (uploadDataEntry) {
  1171. if (uploadDataEntry.parentId !== undefined) {
  1172. parentId = uploadDataEntry.parentId;
  1173. }
  1174. }
  1175. return parentId;
  1176. },
  1177. getResumableFilesData: function() {
  1178. return this._handler.getResumableFilesData();
  1179. },
  1180. getSize: function(id) {
  1181. return this._uploadData.retrieve({
  1182. id: id
  1183. }).size;
  1184. },
  1185. getNetUploads: function() {
  1186. return this._netUploaded;
  1187. },
  1188. getRemainingAllowedItems: function() {
  1189. var allowedItems = this._currentItemLimit;
  1190. if (allowedItems > 0) {
  1191. return allowedItems - this._netUploadedOrQueued;
  1192. }
  1193. return null;
  1194. },
  1195. getUploads: function(optionalFilter) {
  1196. return this._uploadData.retrieve(optionalFilter);
  1197. },
  1198. getUuid: function(id) {
  1199. return this._uploadData.retrieve({
  1200. id: id
  1201. }).uuid;
  1202. },
  1203. log: function(str, level) {
  1204. if (this._options.debug && (!level || level === "info")) {
  1205. qq.log("[Fine Uploader " + qq.version + "] " + str);
  1206. } else if (level && level !== "info") {
  1207. qq.log("[Fine Uploader " + qq.version + "] " + str, level);
  1208. }
  1209. },
  1210. pauseUpload: function(id) {
  1211. var uploadData = this._uploadData.retrieve({
  1212. id: id
  1213. });
  1214. if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
  1215. return false;
  1216. }
  1217. if (qq.indexOf([ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING ], uploadData.status) >= 0) {
  1218. if (this._handler.pause(id)) {
  1219. this._uploadData.setStatus(id, qq.status.PAUSED);
  1220. return true;
  1221. } else {
  1222. this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error");
  1223. }
  1224. } else {
  1225. this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error");
  1226. }
  1227. return false;
  1228. },
  1229. removeFileRef: function(id) {
  1230. this._handler.expunge(id);
  1231. },
  1232. reset: function() {
  1233. this.log("Resetting uploader...");
  1234. this._handler.reset();
  1235. this._storedIds = [];
  1236. this._autoRetries = [];
  1237. this._retryTimeouts = [];
  1238. this._preventRetries = [];
  1239. this._thumbnailUrls = [];
  1240. qq.each(this._buttons, function(idx, button) {
  1241. button.reset();
  1242. });
  1243. this._paramsStore.reset();
  1244. this._endpointStore.reset();
  1245. this._netUploadedOrQueued = 0;
  1246. this._netUploaded = 0;
  1247. this._uploadData.reset();
  1248. this._buttonIdsForFileIds = [];
  1249. this._pasteHandler && this._pasteHandler.reset();
  1250. this._options.session.refreshOnReset && this._refreshSessionData();
  1251. this._succeededSinceLastAllComplete = [];
  1252. this._failedSinceLastAllComplete = [];
  1253. this._totalProgress && this._totalProgress.reset();
  1254. },
  1255. retry: function(id) {
  1256. return this._manualRetry(id);
  1257. },
  1258. scaleImage: function(id, specs) {
  1259. var self = this;
  1260. return qq.Scaler.prototype.scaleImage(id, specs, {
  1261. log: qq.bind(self.log, self),
  1262. getFile: qq.bind(self.getFile, self),
  1263. uploadData: self._uploadData
  1264. });
  1265. },
  1266. setCustomHeaders: function(headers, id) {
  1267. this._customHeadersStore.set(headers, id);
  1268. },
  1269. setDeleteFileCustomHeaders: function(headers, id) {
  1270. this._deleteFileCustomHeadersStore.set(headers, id);
  1271. },
  1272. setDeleteFileEndpoint: function(endpoint, id) {
  1273. this._deleteFileEndpointStore.set(endpoint, id);
  1274. },
  1275. setDeleteFileParams: function(params, id) {
  1276. this._deleteFileParamsStore.set(params, id);
  1277. },
  1278. setEndpoint: function(endpoint, id) {
  1279. this._endpointStore.set(endpoint, id);
  1280. },
  1281. setForm: function(elementOrId) {
  1282. this._updateFormSupportAndParams(elementOrId);
  1283. },
  1284. setItemLimit: function(newItemLimit) {
  1285. this._currentItemLimit = newItemLimit;
  1286. },
  1287. setName: function(id, newName) {
  1288. this._uploadData.updateName(id, newName);
  1289. },
  1290. setParams: function(params, id) {
  1291. this._paramsStore.set(params, id);
  1292. },
  1293. setUuid: function(id, newUuid) {
  1294. return this._uploadData.uuidChanged(id, newUuid);
  1295. },
  1296. setStatus: function(id, newStatus) {
  1297. var fileRecord = this.getUploads({
  1298. id: id
  1299. });
  1300. if (!fileRecord) {
  1301. throw new qq.Error(id + " is not a valid file ID.");
  1302. }
  1303. switch (newStatus) {
  1304. case qq.status.DELETED:
  1305. this._onDeleteComplete(id, null, false);
  1306. break;
  1307. case qq.status.DELETE_FAILED:
  1308. this._onDeleteComplete(id, null, true);
  1309. break;
  1310. default:
  1311. var errorMessage = "Method setStatus called on '" + name + "' not implemented yet for " + newStatus;
  1312. this.log(errorMessage);
  1313. throw new qq.Error(errorMessage);
  1314. }
  1315. },
  1316. uploadStoredFiles: function() {
  1317. if (this._storedIds.length === 0) {
  1318. this._itemError("noFilesError");
  1319. } else {
  1320. this._uploadStoredFiles();
  1321. }
  1322. }
  1323. };
  1324. qq.basePrivateApi = {
  1325. _addCannedFile: function(sessionData) {
  1326. var self = this;
  1327. return this._uploadData.addFile({
  1328. uuid: sessionData.uuid,
  1329. name: sessionData.name,
  1330. size: sessionData.size,
  1331. status: qq.status.UPLOAD_SUCCESSFUL,
  1332. onBeforeStatusChange: function(id) {
  1333. sessionData.deleteFileEndpoint && self.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);
  1334. sessionData.deleteFileParams && self.setDeleteFileParams(sessionData.deleteFileParams, id);
  1335. if (sessionData.thumbnailUrl) {
  1336. self._thumbnailUrls[id] = sessionData.thumbnailUrl;
  1337. }
  1338. self._netUploaded++;
  1339. self._netUploadedOrQueued++;
  1340. }
  1341. });
  1342. },
  1343. _annotateWithButtonId: function(file, associatedInput) {
  1344. if (qq.isFile(file)) {
  1345. file.qqButtonId = this._getButtonId(associatedInput);
  1346. }
  1347. },
  1348. _batchError: function(message) {
  1349. this._options.callbacks.onError(null, null, message, undefined);
  1350. },
  1351. _createDeleteHandler: function() {
  1352. var self = this;
  1353. return new qq.DeleteFileAjaxRequester({
  1354. method: this._options.deleteFile.method.toUpperCase(),
  1355. maxConnections: this._options.maxConnections,
  1356. uuidParamName: this._options.request.uuidName,
  1357. customHeaders: this._deleteFileCustomHeadersStore,
  1358. paramsStore: this._deleteFileParamsStore,
  1359. endpointStore: this._deleteFileEndpointStore,
  1360. cors: this._options.cors,
  1361. log: qq.bind(self.log, self),
  1362. onDelete: function(id) {
  1363. self._onDelete(id);
  1364. self._options.callbacks.onDelete(id);
  1365. },
  1366. onDeleteComplete: function(id, xhrOrXdr, isError) {
  1367. self._onDeleteComplete(id, xhrOrXdr, isError);
  1368. self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
  1369. }
  1370. });
  1371. },
  1372. _createPasteHandler: function() {
  1373. var self = this;
  1374. return new qq.PasteSupport({
  1375. targetElement: this._options.paste.targetElement,
  1376. callbacks: {
  1377. log: qq.bind(self.log, self),
  1378. pasteReceived: function(blob) {
  1379. self._handleCheckedCallback({
  1380. name: "onPasteReceived",
  1381. callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
  1382. onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
  1383. identifier: "pasted image"
  1384. });
  1385. }
  1386. }
  1387. });
  1388. },
  1389. _createStore: function(initialValue, _readOnlyValues_) {
  1390. var store = {}, catchall = initialValue, perIdReadOnlyValues = {}, readOnlyValues = _readOnlyValues_, copy = function(orig) {
  1391. if (qq.isObject(orig)) {
  1392. return qq.extend({}, orig);
  1393. }
  1394. return orig;
  1395. }, getReadOnlyValues = function() {
  1396. if (qq.isFunction(readOnlyValues)) {
  1397. return readOnlyValues();
  1398. }
  1399. return readOnlyValues;
  1400. }, includeReadOnlyValues = function(id, existing) {
  1401. if (readOnlyValues && qq.isObject(existing)) {
  1402. qq.extend(existing, getReadOnlyValues());
  1403. }
  1404. if (perIdReadOnlyValues[id]) {
  1405. qq.extend(existing, perIdReadOnlyValues[id]);
  1406. }
  1407. };
  1408. return {
  1409. set: function(val, id) {
  1410. if (id == null) {
  1411. store = {};
  1412. catchall = copy(val);
  1413. } else {
  1414. store[id] = copy(val);
  1415. }
  1416. },
  1417. get: function(id) {
  1418. var values;
  1419. if (id != null && store[id]) {
  1420. values = store[id];
  1421. } else {
  1422. values = copy(catchall);
  1423. }
  1424. includeReadOnlyValues(id, values);
  1425. return copy(values);
  1426. },
  1427. addReadOnly: function(id, values) {
  1428. if (qq.isObject(store)) {
  1429. if (id === null) {
  1430. if (qq.isFunction(values)) {
  1431. readOnlyValues = values;
  1432. } else {
  1433. readOnlyValues = readOnlyValues || {};
  1434. qq.extend(readOnlyValues, values);
  1435. }
  1436. } else {
  1437. perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};
  1438. qq.extend(perIdReadOnlyValues[id], values);
  1439. }
  1440. }
  1441. },
  1442. remove: function(fileId) {
  1443. return delete store[fileId];
  1444. },
  1445. reset: function() {
  1446. store = {};
  1447. perIdReadOnlyValues = {};
  1448. catchall = initialValue;
  1449. }
  1450. };
  1451. },
  1452. _createUploadDataTracker: function() {
  1453. var self = this;
  1454. return new qq.UploadData({
  1455. getName: function(id) {
  1456. return self.getName(id);
  1457. },
  1458. getUuid: function(id) {
  1459. return self.getUuid(id);
  1460. },
  1461. getSize: function(id) {
  1462. return self.getSize(id);
  1463. },
  1464. onStatusChange: function(id, oldStatus, newStatus) {
  1465. self._onUploadStatusChange(id, oldStatus, newStatus);
  1466. self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
  1467. self._maybeAllComplete(id, newStatus);
  1468. if (self._totalProgress) {
  1469. setTimeout(function() {
  1470. self._totalProgress.onStatusChange(id, oldStatus, newStatus);
  1471. }, 0);
  1472. }
  1473. }
  1474. });
  1475. },
  1476. _createUploadButton: function(spec) {
  1477. var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions, button;
  1478. function allowMultiple() {
  1479. if (qq.supportedFeatures.ajaxUploading) {
  1480. if (self._options.workarounds.iosEmptyVideos && qq.ios() && !qq.ios6() && self._isAllowedExtension(allowedExtensions, ".mov")) {
  1481. return false;
  1482. }
  1483. if (spec.multiple === undefined) {
  1484. return self._options.multiple;
  1485. }
  1486. return spec.multiple;
  1487. }
  1488. return false;
  1489. }
  1490. button = new qq.UploadButton({
  1491. acceptFiles: acceptFiles,
  1492. element: spec.element,
  1493. focusClass: this._options.classes.buttonFocus,
  1494. folders: spec.folders,
  1495. hoverClass: this._options.classes.buttonHover,
  1496. ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash,
  1497. multiple: allowMultiple(),
  1498. name: this._options.request.inputName,
  1499. onChange: function(input) {
  1500. self._onInputChange(input);
  1501. },
  1502. title: spec.title == null ? this._options.text.fileInputTitle : spec.title
  1503. });
  1504. this._disposeSupport.addDisposer(function() {
  1505. button.dispose();
  1506. });
  1507. self._buttons.push(button);
  1508. return button;
  1509. },
  1510. _createUploadHandler: function(additionalOptions, namespace) {
  1511. var self = this, lastOnProgress = {}, options = {
  1512. debug: this._options.debug,
  1513. maxConnections: this._options.maxConnections,
  1514. cors: this._options.cors,
  1515. paramsStore: this._paramsStore,
  1516. endpointStore: this._endpointStore,
  1517. chunking: this._options.chunking,
  1518. resume: this._options.resume,
  1519. blobs: this._options.blobs,
  1520. log: qq.bind(self.log, self),
  1521. preventRetryParam: this._options.retry.preventRetryResponseProperty,
  1522. onProgress: function(id, name, loaded, total) {
  1523. if (loaded < 0 || total < 0) {
  1524. return;
  1525. }
  1526. if (lastOnProgress[id]) {
  1527. if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {
  1528. self._onProgress(id, name, loaded, total);
  1529. self._options.callbacks.onProgress(id, name, loaded, total);
  1530. }
  1531. } else {
  1532. self._onProgress(id, name, loaded, total);
  1533. self._options.callbacks.onProgress(id, name, loaded, total);
  1534. }
  1535. lastOnProgress[id] = {
  1536. loaded: loaded,
  1537. total: total
  1538. };
  1539. },
  1540. onComplete: function(id, name, result, xhr) {
  1541. delete lastOnProgress[id];
  1542. var status = self.getUploads({
  1543. id: id
  1544. }).status, retVal;
  1545. if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {
  1546. return;
  1547. }
  1548. retVal = self._onComplete(id, name, result, xhr);
  1549. if (retVal instanceof qq.Promise) {
  1550. retVal.done(function() {
  1551. self._options.callbacks.onComplete(id, name, result, xhr);
  1552. });
  1553. } else {
  1554. self._options.callbacks.onComplete(id, name, result, xhr);
  1555. }
  1556. },
  1557. onCancel: function(id, name, cancelFinalizationEffort) {
  1558. var promise = new qq.Promise();
  1559. self._handleCheckedCallback({
  1560. name: "onCancel",
  1561. callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
  1562. onFailure: promise.failure,
  1563. onSuccess: function() {
  1564. cancelFinalizationEffort.then(function() {
  1565. self._onCancel(id, name);
  1566. });
  1567. promise.success();
  1568. },
  1569. identifier: id
  1570. });
  1571. return promise;
  1572. },
  1573. onUploadPrep: qq.bind(this._onUploadPrep, this),
  1574. onUpload: function(id, name) {
  1575. self._onUpload(id, name);
  1576. self._options.callbacks.onUpload(id, name);
  1577. },
  1578. onUploadChunk: function(id, name, chunkData) {
  1579. self._onUploadChunk(id, chunkData);
  1580. self._options.callbacks.onUploadChunk(id, name, chunkData);
  1581. },
  1582. onUploadChunkSuccess: function(id, chunkData, result, xhr) {
  1583. self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);
  1584. },
  1585. onResume: function(id, name, chunkData) {
  1586. return self._options.callbacks.onResume(id, name, chunkData);
  1587. },
  1588. onAutoRetry: function(id, name, responseJSON, xhr) {
  1589. return self._onAutoRetry.apply(self, arguments);
  1590. },
  1591. onUuidChanged: function(id, newUuid) {
  1592. self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'");
  1593. self.setUuid(id, newUuid);
  1594. },
  1595. getName: qq.bind(self.getName, self),
  1596. getUuid: qq.bind(self.getUuid, self),
  1597. getSize: qq.bind(self.getSize, self),
  1598. setSize: qq.bind(self._setSize, self),
  1599. getDataByUuid: function(uuid) {
  1600. return self.getUploads({
  1601. uuid: uuid
  1602. });
  1603. },
  1604. isQueued: function(id) {
  1605. var status = self.getUploads({
  1606. id: id
  1607. }).status;
  1608. return status === qq.status.QUEUED || status === qq.status.SUBMITTED || status === qq.status.UPLOAD_RETRYING || status === qq.status.PAUSED;
  1609. },
  1610. getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,
  1611. getIdsInBatch: self._uploadData.getIdsInBatch
  1612. };
  1613. qq.each(this._options.request, function(prop, val) {
  1614. options[prop] = val;
  1615. });
  1616. options.customHeaders = this._customHeadersStore;
  1617. if (additionalOptions) {
  1618. qq.each(additionalOptions, function(key, val) {
  1619. options[key] = val;
  1620. });
  1621. }
  1622. return new qq.UploadHandlerController(options, namespace);
  1623. },
  1624. _fileOrBlobRejected: function(id) {
  1625. this._netUploadedOrQueued--;
  1626. this._uploadData.setStatus(id, qq.status.REJECTED);
  1627. },
  1628. _formatSize: function(bytes) {
  1629. if (bytes === 0) {
  1630. return bytes + this._options.text.sizeSymbols[0];
  1631. }
  1632. var i = -1;
  1633. do {
  1634. bytes = bytes / 1e3;
  1635. i++;
  1636. } while (bytes > 999);
  1637. return Math.max(bytes, .1).toFixed(1) + this._options.text.sizeSymbols[i];
  1638. },
  1639. _generateExtraButtonSpecs: function() {
  1640. var self = this;
  1641. this._extraButtonSpecs = {};
  1642. qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {
  1643. var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry);
  1644. if (multiple === undefined) {
  1645. multiple = self._options.multiple;
  1646. }
  1647. if (extraButtonSpec.validation) {
  1648. qq.extend(validation, extraButtonOptionEntry.validation, true);
  1649. }
  1650. qq.extend(extraButtonSpec, {
  1651. multiple: multiple,
  1652. validation: validation
  1653. }, true);
  1654. self._initExtraButton(extraButtonSpec);
  1655. });
  1656. },
  1657. _getButton: function(buttonId) {
  1658. var extraButtonsSpec = this._extraButtonSpecs[buttonId];
  1659. if (extraButtonsSpec) {
  1660. return extraButtonsSpec.element;
  1661. } else if (buttonId === this._defaultButtonId) {
  1662. return this._options.button;
  1663. }
  1664. },
  1665. _getButtonId: function(buttonOrFileInputOrFile) {
  1666. var inputs, fileInput, fileBlobOrInput = buttonOrFileInputOrFile;
  1667. if (fileBlobOrInput instanceof qq.BlobProxy) {
  1668. fileBlobOrInput = fileBlobOrInput.referenceBlob;
  1669. }
  1670. if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {
  1671. if (qq.isFile(fileBlobOrInput)) {
  1672. return fileBlobOrInput.qqButtonId;
  1673. } else if (fileBlobOrInput.tagName.toLowerCase() === "input" && fileBlobOrInput.type.toLowerCase() === "file") {
  1674. return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
  1675. }
  1676. inputs = fileBlobOrInput.getElementsByTagName("input");
  1677. qq.each(inputs, function(idx, input) {
  1678. if (input.getAttribute("type") === "file") {
  1679. fileInput = input;
  1680. return false;
  1681. }
  1682. });
  1683. if (fileInput) {
  1684. return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
  1685. }
  1686. }
  1687. },
  1688. _getNotFinished: function() {
  1689. return this._uploadData.retrieve({
  1690. status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED ]
  1691. }).length;
  1692. },
  1693. _getValidationBase: function(buttonId) {
  1694. var extraButtonSpec = this._extraButtonSpecs[buttonId];
  1695. return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;
  1696. },
  1697. _getValidationDescriptor: function(fileWrapper) {
  1698. if (fileWrapper.file instanceof qq.BlobProxy) {
  1699. return {
  1700. name: qq.getFilename(fileWrapper.file.referenceBlob),
  1701. size: fileWrapper.file.referenceBlob.size
  1702. };
  1703. }
  1704. return {
  1705. name: this.getUploads({
  1706. id: fileWrapper.id
  1707. }).name,
  1708. size: this.getUploads({
  1709. id: fileWrapper.id
  1710. }).size
  1711. };
  1712. },
  1713. _getValidationDescriptors: function(fileWrappers) {
  1714. var self = this, fileDescriptors = [];
  1715. qq.each(fileWrappers, function(idx, fileWrapper) {
  1716. fileDescriptors.push(self._getValidationDescriptor(fileWrapper));
  1717. });
  1718. return fileDescriptors;
  1719. },
  1720. _handleCameraAccess: function() {
  1721. if (this._options.camera.ios && qq.ios()) {
  1722. var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options;
  1723. if (buttonId && buttonId !== this._defaultButtonId) {
  1724. optionRoot = this._extraButtonSpecs[buttonId];
  1725. }
  1726. optionRoot.multiple = false;
  1727. if (optionRoot.validation.acceptFiles === null) {
  1728. optionRoot.validation.acceptFiles = acceptIosCamera;
  1729. } else {
  1730. optionRoot.validation.acceptFiles += "," + acceptIosCamera;
  1731. }
  1732. qq.each(this._buttons, function(idx, button) {
  1733. if (button.getButtonId() === buttonId) {
  1734. button.setMultiple(optionRoot.multiple);
  1735. button.setAcceptFiles(optionRoot.acceptFiles);
  1736. return false;
  1737. }
  1738. });
  1739. }
  1740. },
  1741. _handleCheckedCallback: function(details) {
  1742. var self = this, callbackRetVal = details.callback();
  1743. if (qq.isGenericPromise(callbackRetVal)) {
  1744. this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
  1745. return callbackRetVal.then(function(successParam) {
  1746. self.log(details.name + " promise success for " + details.identifier);
  1747. details.onSuccess(successParam);
  1748. }, function() {
  1749. if (details.onFailure) {
  1750. self.log(details.name + " promise failure for " + details.identifier);
  1751. details.onFailure();
  1752. } else {
  1753. self.log(details.name + " promise failure for " + details.identifier);
  1754. }
  1755. });
  1756. }
  1757. if (callbackRetVal !== false) {
  1758. details.onSuccess(callbackRetVal);
  1759. } else {
  1760. if (details.onFailure) {
  1761. this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback.");
  1762. details.onFailure();
  1763. } else {
  1764. this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed.");
  1765. }
  1766. }
  1767. return callbackRetVal;
  1768. },
  1769. _handleNewFile: function(file, batchId, newFileWrapperList) {
  1770. var self = this, uuid = qq.getUniqueId(), size = -1, name = qq.getFilename(file), actualFile = file.blob || file, handler = this._customNewFileHandler ? this._customNewFileHandler : qq.bind(self._handleNewFileGeneric, self);
  1771. if (!qq.isInput(actualFile) && actualFile.size >= 0) {
  1772. size = actualFile.size;
  1773. }
  1774. handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, {
  1775. uploadData: self._uploadData,
  1776. paramsStore: self._paramsStore,
  1777. addFileToHandler: function(id, file) {
  1778. self._handler.add(id, file);
  1779. self._netUploadedOrQueued++;
  1780. self._trackButton(id);
  1781. }
  1782. });
  1783. },
  1784. _handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) {
  1785. var id = this._uploadData.addFile({
  1786. uuid: uuid,
  1787. name: name,
  1788. size: size,
  1789. batchId: batchId
  1790. });
  1791. this._handler.add(id, file);
  1792. this._trackButton(id);
  1793. this._netUploadedOrQueued++;
  1794. fileList.push({
  1795. id: id,
  1796. file: file
  1797. });
  1798. },
  1799. _handlePasteSuccess: function(blob, extSuppliedName) {
  1800. var extension = blob.type.split("/")[1], name = extSuppliedName;
  1801. if (name == null) {
  1802. name = this._options.paste.defaultName;
  1803. }
  1804. name += "." + extension;
  1805. this.addFiles({
  1806. name: name,
  1807. blob: blob
  1808. });
  1809. },
  1810. _handleDeleteSuccess: function(id) {
  1811. if (this.getUploads({
  1812. id: id
  1813. }).status !== qq.status.DELETED) {
  1814. var name = this.getName(id);
  1815. this._netUploadedOrQueued--;
  1816. this._netUploaded--;
  1817. this._handler.expunge(id);
  1818. this._uploadData.setStatus(id, qq.status.DELETED);
  1819. this.log("Delete request for '" + name + "' has succeeded.");
  1820. }
  1821. },
  1822. _handleDeleteFailed: function(id, xhrOrXdr) {
  1823. var name = this.getName(id);
  1824. this._uploadData.setStatus(id, qq.status.DELETE_FAILED);
  1825. this.log("Delete request for '" + name + "' has failed.", "error");
  1826. if (!xhrOrXdr || xhrOrXdr.withCredentials === undefined) {
  1827. this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr);
  1828. } else {
  1829. this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr);
  1830. }
  1831. },
  1832. _initExtraButton: function(spec) {
  1833. var button = this._createUploadButton({
  1834. accept: spec.validation.acceptFiles,
  1835. allowedExtensions: spec.validation.allowedExtensions,
  1836. element: spec.element,
  1837. folders: spec.folders,
  1838. multiple: spec.multiple,
  1839. title: spec.fileInputTitle
  1840. });
  1841. this._extraButtonSpecs[button.getButtonId()] = spec;
  1842. },
  1843. _initFormSupportAndParams: function() {
  1844. this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
  1845. if (this._formSupport && this._formSupport.attachedToForm) {
  1846. this._paramsStore = this._createStore(this._options.request.params, this._formSupport.getFormInputsAsObject);
  1847. this._options.autoUpload = this._formSupport.newAutoUpload;
  1848. if (this._formSupport.newEndpoint) {
  1849. this._options.request.endpoint = this._formSupport.newEndpoint;
  1850. }
  1851. } else {
  1852. this._paramsStore = this._createStore(this._options.request.params);
  1853. }
  1854. },
  1855. _isDeletePossible: function() {
  1856. if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) {
  1857. return false;
  1858. }
  1859. if (this._options.cors.expected) {
  1860. if (qq.supportedFeatures.deleteFileCorsXhr) {
  1861. return true;
  1862. }
  1863. if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) {
  1864. return true;
  1865. }
  1866. return false;
  1867. }
  1868. return true;
  1869. },
  1870. _isAllowedExtension: function(allowed, fileName) {
  1871. var valid = false;
  1872. if (!allowed.length) {
  1873. return true;
  1874. }
  1875. qq.each(allowed, function(idx, allowedExt) {
  1876. if (qq.isString(allowedExt)) {
  1877. var extRegex = new RegExp("\\." + allowedExt + "$", "i");
  1878. if (fileName.match(extRegex) != null) {
  1879. valid = true;
  1880. return false;
  1881. }
  1882. }
  1883. });
  1884. return valid;
  1885. },
  1886. _itemError: function(code, maybeNameOrNames, item) {
  1887. var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch;
  1888. function r(name, replacement) {
  1889. message = message.replace(name, replacement);
  1890. }
  1891. qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) {
  1892. if (qq.isString(allowedExtension)) {
  1893. allowedExtensions.push(allowedExtension);
  1894. }
  1895. });
  1896. extensionsForMessage = allowedExtensions.join(", ").toLowerCase();
  1897. r("{file}", this._options.formatFileName(name));
  1898. r("{extensions}", extensionsForMessage);
  1899. r("{sizeLimit}", this._formatSize(validationBase.sizeLimit));
  1900. r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit));
  1901. placeholderMatch = message.match(/(\{\w+\})/g);
  1902. if (placeholderMatch !== null) {
  1903. qq.each(placeholderMatch, function(idx, placeholder) {
  1904. r(placeholder, names[idx]);
  1905. });
  1906. }
  1907. this._options.callbacks.onError(null, name, message, undefined);
  1908. return message;
  1909. },
  1910. _manualRetry: function(id, callback) {
  1911. if (this._onBeforeManualRetry(id)) {
  1912. this._netUploadedOrQueued++;
  1913. this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
  1914. if (callback) {
  1915. callback(id);
  1916. } else {
  1917. this._handler.retry(id);
  1918. }
  1919. return true;
  1920. }
  1921. },
  1922. _maybeAllComplete: function(id, status) {
  1923. var self = this, notFinished = this._getNotFinished();
  1924. if (status === qq.status.UPLOAD_SUCCESSFUL) {
  1925. this._succeededSinceLastAllComplete.push(id);
  1926. } else if (status === qq.status.UPLOAD_FAILED) {
  1927. this._failedSinceLastAllComplete.push(id);
  1928. }
  1929. if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) {
  1930. setTimeout(function() {
  1931. self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete);
  1932. }, 0);
  1933. }
  1934. },
  1935. _maybeHandleIos8SafariWorkaround: function() {
  1936. var self = this;
  1937. if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
  1938. setTimeout(function() {
  1939. window.alert(self._options.messages.unsupportedBrowserIos8Safari);
  1940. }, 0);
  1941. throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari);
  1942. }
  1943. },
  1944. _maybeParseAndSendUploadError: function(id, name, response, xhr) {
  1945. if (!response.success) {
  1946. if (xhr && xhr.status !== 200 && !response.error) {
  1947. this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr);
  1948. } else {
  1949. var errorReason = response.error ? response.error : this._options.text.defaultResponseError;
  1950. this._options.callbacks.onError(id, name, errorReason, xhr);
  1951. }
  1952. }
  1953. },
  1954. _maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {
  1955. var self = this;
  1956. if (items.length > index) {
  1957. if (validItem || !this._options.validation.stopOnFirstInvalidFile) {
  1958. setTimeout(function() {
  1959. var validationDescriptor = self._getValidationDescriptor(items[index]), buttonId = self._getButtonId(items[index].file), button = self._getButton(buttonId);
  1960. self._handleCheckedCallback({
  1961. name: "onValidate",
  1962. callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button),
  1963. onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),
  1964. onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),
  1965. identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size
  1966. });
  1967. }, 0);
  1968. } else if (!validItem) {
  1969. for (;index < items.length; index++) {
  1970. self._fileOrBlobRejected(items[index].id);
  1971. }
  1972. }
  1973. }
  1974. },
  1975. _onAllComplete: function(successful, failed) {
  1976. this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries);
  1977. this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed));
  1978. this._succeededSinceLastAllComplete = [];
  1979. this._failedSinceLastAllComplete = [];
  1980. },
  1981. _onAutoRetry: function(id, name, responseJSON, xhr, callback) {
  1982. var self = this;
  1983. self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];
  1984. if (self._shouldAutoRetry(id, name, responseJSON)) {
  1985. var retryWaitPeriod = self._options.retry.autoAttemptDelay * 1e3;
  1986. self._maybeParseAndSendUploadError.apply(self, arguments);
  1987. self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]);
  1988. self._onBeforeAutoRetry(id, name);
  1989. self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
  1990. self._retryTimeouts[id] = setTimeout(function() {
  1991. self.log("Starting retry for " + name + "...");
  1992. if (callback) {
  1993. callback(id);
  1994. } else {
  1995. self._handler.retry(id);
  1996. }
  1997. }, retryWaitPeriod);
  1998. return true;
  1999. }
  2000. },
  2001. _onBeforeAutoRetry: function(id, name) {
  2002. this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "...");
  2003. },
  2004. _onBeforeManualRetry: function(id) {
  2005. var itemLimit = this._currentItemLimit, fileName;
  2006. if (this._preventRetries[id]) {
  2007. this.log("Retries are forbidden for id " + id, "warn");
  2008. return false;
  2009. } else if (this._handler.isValid(id)) {
  2010. fileName = this.getName(id);
  2011. if (this._options.callbacks.onManualRetry(id, fileName) === false) {
  2012. return false;
  2013. }
  2014. if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) {
  2015. this._itemError("retryFailTooManyItems");
  2016. return false;
  2017. }
  2018. this.log("Retrying upload for '" + fileName + "' (id: " + id + ")...");
  2019. return true;
  2020. } else {
  2021. this.log("'" + id + "' is not a valid file ID", "error");
  2022. return false;
  2023. }
  2024. },
  2025. _onCancel: function(id, name) {
  2026. this._netUploadedOrQueued--;
  2027. clearTimeout(this._retryTimeouts[id]);
  2028. var storedItemIndex = qq.indexOf(this._storedIds, id);
  2029. if (!this._options.autoUpload && storedItemIndex >= 0) {
  2030. this._storedIds.splice(storedItemIndex, 1);
  2031. }
  2032. this._uploadData.setStatus(id, qq.status.CANCELED);
  2033. },
  2034. _onComplete: function(id, name, result, xhr) {
  2035. if (!result.success) {
  2036. this._netUploadedOrQueued--;
  2037. this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);
  2038. if (result[this._options.retry.preventRetryResponseProperty] === true) {
  2039. this._preventRetries[id] = true;
  2040. }
  2041. } else {
  2042. if (result.thumbnailUrl) {
  2043. this._thumbnailUrls[id] = result.thumbnailUrl;
  2044. }
  2045. this._netUploaded++;
  2046. this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);
  2047. }
  2048. this._maybeParseAndSendUploadError(id, name, result, xhr);
  2049. return result.success ? true : false;
  2050. },
  2051. _onDelete: function(id) {
  2052. this._uploadData.setStatus(id, qq.status.DELETING);
  2053. },
  2054. _onDeleteComplete: function(id, xhrOrXdr, isError) {
  2055. var name = this.getName(id);
  2056. if (isError) {
  2057. this._handleDeleteFailed(id, xhrOrXdr);
  2058. } else {
  2059. this._handleDeleteSuccess(id);
  2060. }
  2061. },
  2062. _onInputChange: function(input) {
  2063. var fileIndex;
  2064. if (qq.supportedFeatures.ajaxUploading) {
  2065. for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) {
  2066. this._annotateWithButtonId(input.files[fileIndex], input);
  2067. }
  2068. this.addFiles(input.files);
  2069. } else if (input.value.length > 0) {
  2070. this.addFiles(input);
  2071. }
  2072. qq.each(this._buttons, function(idx, button) {
  2073. button.reset();
  2074. });
  2075. },
  2076. _onProgress: function(id, name, loaded, total) {
  2077. this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total);
  2078. },
  2079. _onSubmit: function(id, name) {},
  2080. _onSubmitCallbackSuccess: function(id, name) {
  2081. this._onSubmit.apply(this, arguments);
  2082. this._uploadData.setStatus(id, qq.status.SUBMITTED);
  2083. this._onSubmitted.apply(this, arguments);
  2084. if (this._options.autoUpload) {
  2085. this._options.callbacks.onSubmitted.apply(this, arguments);
  2086. this._uploadFile(id);
  2087. } else {
  2088. this._storeForLater(id);
  2089. this._options.callbacks.onSubmitted.apply(this, arguments);
  2090. }
  2091. },
  2092. _onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) {
  2093. var uuid = this.getUuid(id), adjustedOnSuccessCallback;
  2094. if (onSuccessCallback) {
  2095. adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams);
  2096. }
  2097. if (this._isDeletePossible()) {
  2098. this._handleCheckedCallback({
  2099. name: "onSubmitDelete",
  2100. callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),
  2101. onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams),
  2102. identifier: id
  2103. });
  2104. return true;
  2105. } else {
  2106. this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn");
  2107. return false;
  2108. }
  2109. },
  2110. _onSubmitted: function(id) {},
  2111. _onTotalProgress: function(loaded, total) {
  2112. this._options.callbacks.onTotalProgress(loaded, total);
  2113. },
  2114. _onUploadPrep: function(id) {},
  2115. _onUpload: function(id, name) {
  2116. this._uploadData.setStatus(id, qq.status.UPLOADING);
  2117. },
  2118. _onUploadChunk: function(id, chunkData) {},
  2119. _onUploadStatusChange: function(id, oldStatus, newStatus) {
  2120. if (newStatus === qq.status.PAUSED) {
  2121. clearTimeout(this._retryTimeouts[id]);
  2122. }
  2123. },
  2124. _onValidateBatchCallbackFailure: function(fileWrappers) {
  2125. var self = this;
  2126. qq.each(fileWrappers, function(idx, fileWrapper) {
  2127. self._fileOrBlobRejected(fileWrapper.id);
  2128. });
  2129. },
  2130. _onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) {
  2131. var errorMessage, itemLimit = this._currentItemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued;
  2132. if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {
  2133. if (items.length > 0) {
  2134. this._handleCheckedCallback({
  2135. name: "onValidate",
  2136. callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button),
  2137. onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),
  2138. onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),
  2139. identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size
  2140. });
  2141. } else {
  2142. this._itemError("noFilesError");
  2143. }
  2144. } else {
  2145. this._onValidateBatchCallbackFailure(items);
  2146. errorMessage = this._options.messages.tooManyItemsError.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued).replace(/\{itemLimit\}/g, itemLimit);
  2147. this._batchError(errorMessage);
  2148. }
  2149. },
  2150. _onValidateCallbackFailure: function(items, index, params, endpoint) {
  2151. var nextIndex = index + 1;
  2152. this._fileOrBlobRejected(items[index].id, items[index].file.name);
  2153. this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
  2154. },
  2155. _onValidateCallbackSuccess: function(items, index, params, endpoint) {
  2156. var self = this, nextIndex = index + 1, validationDescriptor = this._getValidationDescriptor(items[index]);
  2157. this._validateFileOrBlobData(items[index], validationDescriptor).then(function() {
  2158. self._upload(items[index].id, params, endpoint);
  2159. self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint);
  2160. }, function() {
  2161. self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
  2162. });
  2163. },
  2164. _prepareItemsForUpload: function(items, params, endpoint) {
  2165. if (items.length === 0) {
  2166. this._itemError("noFilesError");
  2167. return;
  2168. }
  2169. var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId);
  2170. this._handleCheckedCallback({
  2171. name: "onValidateBatch",
  2172. callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button),
  2173. onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button),
  2174. onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items),
  2175. identifier: "batch validation"
  2176. });
  2177. },
  2178. _preventLeaveInProgress: function() {
  2179. var self = this;
  2180. this._disposeSupport.attach(window, "beforeunload", function(e) {
  2181. if (self.getInProgress()) {
  2182. e = e || window.event;
  2183. e.returnValue = self._options.messages.onLeave;
  2184. return self._options.messages.onLeave;
  2185. }
  2186. });
  2187. },
  2188. _refreshSessionData: function() {
  2189. var self = this, options = this._options.session;
  2190. if (qq.Session && this._options.session.endpoint != null) {
  2191. if (!this._session) {
  2192. qq.extend(options, {
  2193. cors: this._options.cors
  2194. });
  2195. options.log = qq.bind(this.log, this);
  2196. options.addFileRecord = qq.bind(this._addCannedFile, this);
  2197. this._session = new qq.Session(options);
  2198. }
  2199. setTimeout(function() {
  2200. self._session.refresh().then(function(response, xhrOrXdr) {
  2201. self._sessionRequestComplete();
  2202. self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr);
  2203. }, function(response, xhrOrXdr) {
  2204. self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr);
  2205. });
  2206. }, 0);
  2207. }
  2208. },
  2209. _sessionRequestComplete: function() {},
  2210. _setSize: function(id, newSize) {
  2211. this._uploadData.updateSize(id, newSize);
  2212. this._totalProgress && this._totalProgress.onNewSize(id);
  2213. },
  2214. _shouldAutoRetry: function(id, name, responseJSON) {
  2215. var uploadData = this._uploadData.retrieve({
  2216. id: id
  2217. });
  2218. if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) {
  2219. if (this._autoRetries[id] === undefined) {
  2220. this._autoRetries[id] = 0;
  2221. }
  2222. if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) {
  2223. this._autoRetries[id] += 1;
  2224. return true;
  2225. }
  2226. }
  2227. return false;
  2228. },
  2229. _storeForLater: function(id) {
  2230. this._storedIds.push(id);
  2231. },
  2232. _trackButton: function(id) {
  2233. var buttonId;
  2234. if (qq.supportedFeatures.ajaxUploading) {
  2235. buttonId = this._handler.getFile(id).qqButtonId;
  2236. } else {
  2237. buttonId = this._getButtonId(this._handler.getInput(id));
  2238. }
  2239. if (buttonId) {
  2240. this._buttonIdsForFileIds[id] = buttonId;
  2241. }
  2242. },
  2243. _updateFormSupportAndParams: function(formElementOrId) {
  2244. this._options.form.element = formElementOrId;
  2245. this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
  2246. if (this._formSupport && this._formSupport.attachedToForm) {
  2247. this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject);
  2248. this._options.autoUpload = this._formSupport.newAutoUpload;
  2249. if (this._formSupport.newEndpoint) {
  2250. this.setEndpoint(this._formSupport.newEndpoint);
  2251. }
  2252. }
  2253. },
  2254. _upload: function(id, params, endpoint) {
  2255. var name = this.getName(id);
  2256. if (params) {
  2257. this.setParams(params, id);
  2258. }
  2259. if (endpoint) {
  2260. this.setEndpoint(endpoint, id);
  2261. }
  2262. this._handleCheckedCallback({
  2263. name: "onSubmit",
  2264. callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),
  2265. onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),
  2266. onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),
  2267. identifier: id
  2268. });
  2269. },
  2270. _uploadFile: function(id) {
  2271. if (!this._handler.upload(id)) {
  2272. this._uploadData.setStatus(id, qq.status.QUEUED);
  2273. }
  2274. },
  2275. _uploadStoredFiles: function() {
  2276. var idToUpload, stillSubmitting, self = this;
  2277. while (this._storedIds.length) {
  2278. idToUpload = this._storedIds.shift();
  2279. this._uploadFile(idToUpload);
  2280. }
  2281. stillSubmitting = this.getUploads({
  2282. status: qq.status.SUBMITTING
  2283. }).length;
  2284. if (stillSubmitting) {
  2285. qq.log("Still waiting for " + stillSubmitting + " files to clear submit queue. Will re-parse stored IDs array shortly.");
  2286. setTimeout(function() {
  2287. self._uploadStoredFiles();
  2288. }, 1e3);
  2289. }
  2290. },
  2291. _validateFileOrBlobData: function(fileWrapper, validationDescriptor) {
  2292. var self = this, file = function() {
  2293. if (fileWrapper.file instanceof qq.BlobProxy) {
  2294. return fileWrapper.file.referenceBlob;
  2295. }
  2296. return fileWrapper.file;
  2297. }(), name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(fileWrapper.file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise();
  2298. validityChecker.then(function() {}, function() {
  2299. self._fileOrBlobRejected(fileWrapper.id, name);
  2300. });
  2301. if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) {
  2302. this._itemError("typeError", name, file);
  2303. return validityChecker.failure();
  2304. }
  2305. if (!this._options.validation.allowEmpty && size === 0) {
  2306. this._itemError("emptyError", name, file);
  2307. return validityChecker.failure();
  2308. }
  2309. if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) {
  2310. this._itemError("sizeError", name, file);
  2311. return validityChecker.failure();
  2312. }
  2313. if (size > 0 && size < validationBase.minSizeLimit) {
  2314. this._itemError("minSizeError", name, file);
  2315. return validityChecker.failure();
  2316. }
  2317. if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) {
  2318. new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(validityChecker.success, function(errorCode) {
  2319. self._itemError(errorCode + "ImageError", name, file);
  2320. validityChecker.failure();
  2321. });
  2322. } else {
  2323. validityChecker.success();
  2324. }
  2325. return validityChecker;
  2326. },
  2327. _wrapCallbacks: function() {
  2328. var self, safeCallback, prop;
  2329. self = this;
  2330. safeCallback = function(name, callback, args) {
  2331. var errorMsg;
  2332. try {
  2333. return callback.apply(self, args);
  2334. } catch (exception) {
  2335. errorMsg = exception.message || exception.toString();
  2336. self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error");
  2337. }
  2338. };
  2339. for (prop in this._options.callbacks) {
  2340. (function() {
  2341. var callbackName, callbackFunc;
  2342. callbackName = prop;
  2343. callbackFunc = self._options.callbacks[callbackName];
  2344. self._options.callbacks[callbackName] = function() {
  2345. return safeCallback(callbackName, callbackFunc, arguments);
  2346. };
  2347. })();
  2348. }
  2349. }
  2350. };
  2351. })();
  2352. (function() {
  2353. "use strict";
  2354. qq.FineUploaderBasic = function(o) {
  2355. var self = this;
  2356. this._options = {
  2357. debug: false,
  2358. button: null,
  2359. multiple: true,
  2360. maxConnections: 3,
  2361. disableCancelForFormUploads: false,
  2362. autoUpload: true,
  2363. request: {
  2364. customHeaders: {},
  2365. endpoint: "/server/upload",
  2366. filenameParam: "qqfilename",
  2367. forceMultipart: true,
  2368. inputName: "qqfile",
  2369. method: "POST",
  2370. params: {},
  2371. paramsInBody: true,
  2372. totalFileSizeName: "qqtotalfilesize",
  2373. uuidName: "qquuid"
  2374. },
  2375. validation: {
  2376. allowedExtensions: [],
  2377. sizeLimit: 0,
  2378. minSizeLimit: 0,
  2379. itemLimit: 0,
  2380. stopOnFirstInvalidFile: true,
  2381. acceptFiles: null,
  2382. image: {
  2383. maxHeight: 0,
  2384. maxWidth: 0,
  2385. minHeight: 0,
  2386. minWidth: 0
  2387. },
  2388. allowEmpty: false
  2389. },
  2390. callbacks: {
  2391. onSubmit: function(id, name) {},
  2392. onSubmitted: function(id, name) {},
  2393. onComplete: function(id, name, responseJSON, maybeXhr) {},
  2394. onAllComplete: function(successful, failed) {},
  2395. onCancel: function(id, name) {},
  2396. onUpload: function(id, name) {},
  2397. onUploadChunk: function(id, name, chunkData) {},
  2398. onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},
  2399. onResume: function(id, fileName, chunkData) {},
  2400. onProgress: function(id, name, loaded, total) {},
  2401. onTotalProgress: function(loaded, total) {},
  2402. onError: function(id, name, reason, maybeXhrOrXdr) {},
  2403. onAutoRetry: function(id, name, attemptNumber) {},
  2404. onManualRetry: function(id, name) {},
  2405. onValidateBatch: function(fileOrBlobData) {},
  2406. onValidate: function(fileOrBlobData) {},
  2407. onSubmitDelete: function(id) {},
  2408. onDelete: function(id) {},
  2409. onDeleteComplete: function(id, xhrOrXdr, isError) {},
  2410. onPasteReceived: function(blob) {},
  2411. onStatusChange: function(id, oldStatus, newStatus) {},
  2412. onSessionRequestComplete: function(response, success, xhrOrXdr) {}
  2413. },
  2414. messages: {
  2415. typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
  2416. sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
  2417. minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
  2418. emptyError: "{file} is empty, please select files again without it.",
  2419. noFilesError: "No files to upload.",
  2420. tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
  2421. maxHeightImageError: "Image is too tall.",
  2422. maxWidthImageError: "Image is too wide.",
  2423. minHeightImageError: "Image is not tall enough.",
  2424. minWidthImageError: "Image is not wide enough.",
  2425. retryFailTooManyItems: "Retry failed - you have reached your file limit.",
  2426. onLeave: "The files are being uploaded, if you leave now the upload will be canceled.",
  2427. unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues."
  2428. },
  2429. retry: {
  2430. enableAuto: false,
  2431. maxAutoAttempts: 3,
  2432. autoAttemptDelay: 5,
  2433. preventRetryResponseProperty: "preventRetry"
  2434. },
  2435. classes: {
  2436. buttonHover: "qq-upload-button-hover",
  2437. buttonFocus: "qq-upload-button-focus"
  2438. },
  2439. chunking: {
  2440. enabled: false,
  2441. concurrent: {
  2442. enabled: false
  2443. },
  2444. mandatory: false,
  2445. paramNames: {
  2446. partIndex: "qqpartindex",
  2447. partByteOffset: "qqpartbyteoffset",
  2448. chunkSize: "qqchunksize",
  2449. totalFileSize: "qqtotalfilesize",
  2450. totalParts: "qqtotalparts"
  2451. },
  2452. partSize: 2e6,
  2453. success: {
  2454. endpoint: null
  2455. }
  2456. },
  2457. resume: {
  2458. enabled: false,
  2459. recordsExpireIn: 7,
  2460. paramNames: {
  2461. resuming: "qqresume"
  2462. }
  2463. },
  2464. formatFileName: function(fileOrBlobName) {
  2465. return fileOrBlobName;
  2466. },
  2467. text: {
  2468. defaultResponseError: "Upload failure reason unknown",
  2469. fileInputTitle: "file input",
  2470. sizeSymbols: [ "kB", "MB", "GB", "TB", "PB", "EB" ]
  2471. },
  2472. deleteFile: {
  2473. enabled: false,
  2474. method: "DELETE",
  2475. endpoint: "/server/upload",
  2476. customHeaders: {},
  2477. params: {}
  2478. },
  2479. cors: {
  2480. expected: false,
  2481. sendCredentials: false,
  2482. allowXdr: false
  2483. },
  2484. blobs: {
  2485. defaultName: "misc_data"
  2486. },
  2487. paste: {
  2488. targetElement: null,
  2489. defaultName: "pasted_image"
  2490. },
  2491. camera: {
  2492. ios: false,
  2493. button: null
  2494. },
  2495. extraButtons: [],
  2496. session: {
  2497. endpoint: null,
  2498. params: {},
  2499. customHeaders: {},
  2500. refreshOnReset: true
  2501. },
  2502. form: {
  2503. element: "qq-form",
  2504. autoUpload: false,
  2505. interceptSubmit: true
  2506. },
  2507. scaling: {
  2508. customResizer: null,
  2509. sendOriginal: true,
  2510. orient: true,
  2511. defaultType: null,
  2512. defaultQuality: 80,
  2513. failureText: "Failed to scale",
  2514. includeExif: false,
  2515. sizes: []
  2516. },
  2517. workarounds: {
  2518. iosEmptyVideos: true,
  2519. ios8SafariUploads: true,
  2520. ios8BrowserCrash: false
  2521. }
  2522. };
  2523. qq.extend(this._options, o, true);
  2524. this._buttons = [];
  2525. this._extraButtonSpecs = {};
  2526. this._buttonIdsForFileIds = [];
  2527. this._wrapCallbacks();
  2528. this._disposeSupport = new qq.DisposeSupport();
  2529. this._storedIds = [];
  2530. this._autoRetries = [];
  2531. this._retryTimeouts = [];
  2532. this._preventRetries = [];
  2533. this._thumbnailUrls = [];
  2534. this._netUploadedOrQueued = 0;
  2535. this._netUploaded = 0;
  2536. this._uploadData = this._createUploadDataTracker();
  2537. this._initFormSupportAndParams();
  2538. this._customHeadersStore = this._createStore(this._options.request.customHeaders);
  2539. this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders);
  2540. this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params);
  2541. this._endpointStore = this._createStore(this._options.request.endpoint);
  2542. this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint);
  2543. this._handler = this._createUploadHandler();
  2544. this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler();
  2545. if (this._options.button) {
  2546. this._defaultButtonId = this._createUploadButton({
  2547. element: this._options.button,
  2548. title: this._options.text.fileInputTitle
  2549. }).getButtonId();
  2550. }
  2551. this._generateExtraButtonSpecs();
  2552. this._handleCameraAccess();
  2553. if (this._options.paste.targetElement) {
  2554. if (qq.PasteSupport) {
  2555. this._pasteHandler = this._createPasteHandler();
  2556. } else {
  2557. this.log("Paste support module not found", "error");
  2558. }
  2559. }
  2560. this._preventLeaveInProgress();
  2561. this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this));
  2562. this._refreshSessionData();
  2563. this._succeededSinceLastAllComplete = [];
  2564. this._failedSinceLastAllComplete = [];
  2565. this._scaler = qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this)) || {};
  2566. if (this._scaler.enabled) {
  2567. this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler);
  2568. }
  2569. if (qq.TotalProgress && qq.supportedFeatures.progressBar) {
  2570. this._totalProgress = new qq.TotalProgress(qq.bind(this._onTotalProgress, this), function(id) {
  2571. var entry = self._uploadData.retrieve({
  2572. id: id
  2573. });
  2574. return entry && entry.size || 0;
  2575. });
  2576. }
  2577. this._currentItemLimit = this._options.validation.itemLimit;
  2578. };
  2579. qq.FineUploaderBasic.prototype = qq.basePublicApi;
  2580. qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi);
  2581. })();
  2582. qq.AjaxRequester = function(o) {
  2583. "use strict";
  2584. var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = {
  2585. acceptHeader: null,
  2586. validMethods: [ "PATCH", "POST", "PUT" ],
  2587. method: "POST",
  2588. contentType: "application/x-www-form-urlencoded",
  2589. maxConnections: 3,
  2590. customHeaders: {},
  2591. endpointStore: {},
  2592. paramsStore: {},
  2593. mandatedParams: {},
  2594. allowXRequestedWithAndCacheControl: true,
  2595. successfulResponseCodes: {
  2596. DELETE: [ 200, 202, 204 ],
  2597. PATCH: [ 200, 201, 202, 203, 204 ],
  2598. POST: [ 200, 201, 202, 203, 204 ],
  2599. PUT: [ 200, 201, 202, 203, 204 ],
  2600. GET: [ 200 ]
  2601. },
  2602. cors: {
  2603. expected: false,
  2604. sendCredentials: false
  2605. },
  2606. log: function(str, level) {},
  2607. onSend: function(id) {},
  2608. onComplete: function(id, xhrOrXdr, isError) {},
  2609. onProgress: null
  2610. };
  2611. qq.extend(options, o);
  2612. log = options.log;
  2613. if (qq.indexOf(options.validMethods, options.method) < 0) {
  2614. throw new Error("'" + options.method + "' is not a supported method for this type of request!");
  2615. }
  2616. function isSimpleMethod() {
  2617. return qq.indexOf([ "GET", "POST", "HEAD" ], options.method) >= 0;
  2618. }
  2619. function containsNonSimpleHeaders(headers) {
  2620. var containsNonSimple = false;
  2621. qq.each(containsNonSimple, function(idx, header) {
  2622. if (qq.indexOf([ "Accept", "Accept-Language", "Content-Language", "Content-Type" ], header) < 0) {
  2623. containsNonSimple = true;
  2624. return false;
  2625. }
  2626. });
  2627. return containsNonSimple;
  2628. }
  2629. function isXdr(xhr) {
  2630. return options.cors.expected && xhr.withCredentials === undefined;
  2631. }
  2632. function getCorsAjaxTransport() {
  2633. var xhrOrXdr;
  2634. if (window.XMLHttpRequest || window.ActiveXObject) {
  2635. xhrOrXdr = qq.createXhrInstance();
  2636. if (xhrOrXdr.withCredentials === undefined) {
  2637. xhrOrXdr = new XDomainRequest();
  2638. xhrOrXdr.onload = function() {};
  2639. xhrOrXdr.onerror = function() {};
  2640. xhrOrXdr.ontimeout = function() {};
  2641. xhrOrXdr.onprogress = function() {};
  2642. }
  2643. }
  2644. return xhrOrXdr;
  2645. }
  2646. function getXhrOrXdr(id, suppliedXhr) {
  2647. var xhrOrXdr = requestData[id].xhr;
  2648. if (!xhrOrXdr) {
  2649. if (suppliedXhr) {
  2650. xhrOrXdr = suppliedXhr;
  2651. } else {
  2652. if (options.cors.expected) {
  2653. xhrOrXdr = getCorsAjaxTransport();
  2654. } else {
  2655. xhrOrXdr = qq.createXhrInstance();
  2656. }
  2657. }
  2658. requestData[id].xhr = xhrOrXdr;
  2659. }
  2660. return xhrOrXdr;
  2661. }
  2662. function dequeue(id) {
  2663. var i = qq.indexOf(queue, id), max = options.maxConnections, nextId;
  2664. delete requestData[id];
  2665. queue.splice(i, 1);
  2666. if (queue.length >= max && i < max) {
  2667. nextId = queue[max - 1];
  2668. sendRequest(nextId);
  2669. }
  2670. }
  2671. function onComplete(id, xdrError) {
  2672. var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true;
  2673. dequeue(id);
  2674. if (isError) {
  2675. log(method + " request for " + id + " has failed", "error");
  2676. } else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) {
  2677. isError = true;
  2678. log(method + " request for " + id + " has failed - response code " + xhr.status, "error");
  2679. }
  2680. options.onComplete(id, xhr, isError);
  2681. }
  2682. function getParams(id) {
  2683. var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params;
  2684. if (options.paramsStore.get) {
  2685. params = options.paramsStore.get(id);
  2686. }
  2687. if (onDemandParams) {
  2688. qq.each(onDemandParams, function(name, val) {
  2689. params = params || {};
  2690. params[name] = val;
  2691. });
  2692. }
  2693. if (mandatedParams) {
  2694. qq.each(mandatedParams, function(name, val) {
  2695. params = params || {};
  2696. params[name] = val;
  2697. });
  2698. }
  2699. return params;
  2700. }
  2701. function sendRequest(id, optXhr) {
  2702. var xhr = getXhrOrXdr(id, optXhr), method = options.method, params = getParams(id), payload = requestData[id].payload, url;
  2703. options.onSend(id);
  2704. url = createUrl(id, params, requestData[id].additionalQueryParams);
  2705. if (isXdr(xhr)) {
  2706. xhr.onload = getXdrLoadHandler(id);
  2707. xhr.onerror = getXdrErrorHandler(id);
  2708. } else {
  2709. xhr.onreadystatechange = getXhrReadyStateChangeHandler(id);
  2710. }
  2711. registerForUploadProgress(id);
  2712. xhr.open(method, url, true);
  2713. if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) {
  2714. xhr.withCredentials = true;
  2715. }
  2716. setHeaders(id);
  2717. log("Sending " + method + " request for " + id);
  2718. if (payload) {
  2719. xhr.send(payload);
  2720. } else if (shouldParamsBeInQueryString || !params) {
  2721. xhr.send();
  2722. } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) {
  2723. xhr.send(qq.obj2url(params, ""));
  2724. } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) {
  2725. xhr.send(JSON.stringify(params));
  2726. } else {
  2727. xhr.send(params);
  2728. }
  2729. return xhr;
  2730. }
  2731. function createUrl(id, params, additionalQueryParams) {
  2732. var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath;
  2733. if (addToPath != undefined) {
  2734. endpoint += "/" + addToPath;
  2735. }
  2736. if (shouldParamsBeInQueryString && params) {
  2737. endpoint = qq.obj2url(params, endpoint);
  2738. }
  2739. if (additionalQueryParams) {
  2740. endpoint = qq.obj2url(additionalQueryParams, endpoint);
  2741. }
  2742. return endpoint;
  2743. }
  2744. function getXhrReadyStateChangeHandler(id) {
  2745. return function() {
  2746. if (getXhrOrXdr(id).readyState === 4) {
  2747. onComplete(id);
  2748. }
  2749. };
  2750. }
  2751. function registerForUploadProgress(id) {
  2752. var onProgress = options.onProgress;
  2753. if (onProgress) {
  2754. getXhrOrXdr(id).upload.onprogress = function(e) {
  2755. if (e.lengthComputable) {
  2756. onProgress(id, e.loaded, e.total);
  2757. }
  2758. };
  2759. }
  2760. }
  2761. function getXdrLoadHandler(id) {
  2762. return function() {
  2763. onComplete(id);
  2764. };
  2765. }
  2766. function getXdrErrorHandler(id) {
  2767. return function() {
  2768. onComplete(id, true);
  2769. };
  2770. }
  2771. function setHeaders(id) {
  2772. var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {};
  2773. if (!isXdr(xhr)) {
  2774. options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader);
  2775. if (options.allowXRequestedWithAndCacheControl) {
  2776. if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) {
  2777. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  2778. xhr.setRequestHeader("Cache-Control", "no-cache");
  2779. }
  2780. }
  2781. if (options.contentType && (method === "POST" || method === "PUT")) {
  2782. xhr.setRequestHeader("Content-Type", options.contentType);
  2783. }
  2784. qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders);
  2785. qq.extend(allHeaders, onDemandHeaders);
  2786. qq.each(allHeaders, function(name, val) {
  2787. xhr.setRequestHeader(name, val);
  2788. });
  2789. }
  2790. }
  2791. function isResponseSuccessful(responseCode) {
  2792. return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0;
  2793. }
  2794. function prepareToSend(id, optXhr, addToPath, additionalParams, additionalQueryParams, additionalHeaders, payload) {
  2795. requestData[id] = {
  2796. addToPath: addToPath,
  2797. additionalParams: additionalParams,
  2798. additionalQueryParams: additionalQueryParams,
  2799. additionalHeaders: additionalHeaders,
  2800. payload: payload
  2801. };
  2802. var len = queue.push(id);
  2803. if (len <= options.maxConnections) {
  2804. return sendRequest(id, optXhr);
  2805. }
  2806. }
  2807. shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE";
  2808. qq.extend(this, {
  2809. initTransport: function(id) {
  2810. var path, params, headers, payload, cacheBuster, additionalQueryParams;
  2811. return {
  2812. withPath: function(appendToPath) {
  2813. path = appendToPath;
  2814. return this;
  2815. },
  2816. withParams: function(additionalParams) {
  2817. params = additionalParams;
  2818. return this;
  2819. },
  2820. withQueryParams: function(_additionalQueryParams_) {
  2821. additionalQueryParams = _additionalQueryParams_;
  2822. return this;
  2823. },
  2824. withHeaders: function(additionalHeaders) {
  2825. headers = additionalHeaders;
  2826. return this;
  2827. },
  2828. withPayload: function(thePayload) {
  2829. payload = thePayload;
  2830. return this;
  2831. },
  2832. withCacheBuster: function() {
  2833. cacheBuster = true;
  2834. return this;
  2835. },
  2836. send: function(optXhr) {
  2837. if (cacheBuster && qq.indexOf([ "GET", "DELETE" ], options.method) >= 0) {
  2838. params.qqtimestamp = new Date().getTime();
  2839. }
  2840. return prepareToSend(id, optXhr, path, params, additionalQueryParams, headers, payload);
  2841. }
  2842. };
  2843. },
  2844. canceled: function(id) {
  2845. dequeue(id);
  2846. }
  2847. });
  2848. };
  2849. qq.UploadHandler = function(spec) {
  2850. "use strict";
  2851. var proxy = spec.proxy, fileState = {}, onCancel = proxy.onCancel, getName = proxy.getName;
  2852. qq.extend(this, {
  2853. add: function(id, fileItem) {
  2854. fileState[id] = fileItem;
  2855. fileState[id].temp = {};
  2856. },
  2857. cancel: function(id) {
  2858. var self = this, cancelFinalizationEffort = new qq.Promise(), onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort);
  2859. onCancelRetVal.then(function() {
  2860. if (self.isValid(id)) {
  2861. fileState[id].canceled = true;
  2862. self.expunge(id);
  2863. }
  2864. cancelFinalizationEffort.success();
  2865. });
  2866. },
  2867. expunge: function(id) {
  2868. delete fileState[id];
  2869. },
  2870. getThirdPartyFileId: function(id) {
  2871. return fileState[id].key;
  2872. },
  2873. isValid: function(id) {
  2874. return fileState[id] !== undefined;
  2875. },
  2876. reset: function() {
  2877. fileState = {};
  2878. },
  2879. _getFileState: function(id) {
  2880. return fileState[id];
  2881. },
  2882. _setThirdPartyFileId: function(id, thirdPartyFileId) {
  2883. fileState[id].key = thirdPartyFileId;
  2884. },
  2885. _wasCanceled: function(id) {
  2886. return !!fileState[id].canceled;
  2887. }
  2888. });
  2889. };
  2890. qq.UploadHandlerController = function(o, namespace) {
  2891. "use strict";
  2892. var controller = this, chunkingPossible = false, concurrentChunkingPossible = false, chunking, preventRetryResponse, log, handler, options = {
  2893. paramsStore: {},
  2894. maxConnections: 3,
  2895. chunking: {
  2896. enabled: false,
  2897. multiple: {
  2898. enabled: false
  2899. }
  2900. },
  2901. log: function(str, level) {},
  2902. onProgress: function(id, fileName, loaded, total) {},
  2903. onComplete: function(id, fileName, response, xhr) {},
  2904. onCancel: function(id, fileName) {},
  2905. onUploadPrep: function(id) {},
  2906. onUpload: function(id, fileName) {},
  2907. onUploadChunk: function(id, fileName, chunkData) {},
  2908. onUploadChunkSuccess: function(id, chunkData, response, xhr) {},
  2909. onAutoRetry: function(id, fileName, response, xhr) {},
  2910. onResume: function(id, fileName, chunkData) {},
  2911. onUuidChanged: function(id, newUuid) {},
  2912. getName: function(id) {},
  2913. setSize: function(id, newSize) {},
  2914. isQueued: function(id) {},
  2915. getIdsInProxyGroup: function(id) {},
  2916. getIdsInBatch: function(id) {}
  2917. }, chunked = {
  2918. done: function(id, chunkIdx, response, xhr) {
  2919. var chunkData = handler._getChunkData(id, chunkIdx);
  2920. handler._getFileState(id).attemptingResume = false;
  2921. delete handler._getFileState(id).temp.chunkProgress[chunkIdx];
  2922. handler._getFileState(id).loaded += chunkData.size;
  2923. options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr);
  2924. },
  2925. finalize: function(id) {
  2926. var size = options.getSize(id), name = options.getName(id);
  2927. log("All chunks have been uploaded for " + id + " - finalizing....");
  2928. handler.finalizeChunks(id).then(function(response, xhr) {
  2929. log("Finalize successful for " + id);
  2930. var normaizedResponse = upload.normalizeResponse(response, true);
  2931. options.onProgress(id, name, size, size);
  2932. handler._maybeDeletePersistedChunkData(id);
  2933. upload.cleanup(id, normaizedResponse, xhr);
  2934. }, function(response, xhr) {
  2935. var normaizedResponse = upload.normalizeResponse(response, false);
  2936. log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error");
  2937. if (normaizedResponse.reset) {
  2938. chunked.reset(id);
  2939. }
  2940. if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) {
  2941. upload.cleanup(id, normaizedResponse, xhr);
  2942. }
  2943. });
  2944. },
  2945. handleFailure: function(chunkIdx, id, response, xhr) {
  2946. var name = options.getName(id);
  2947. log("Chunked upload request failed for " + id + ", chunk " + chunkIdx);
  2948. handler.clearCachedChunk(id, chunkIdx);
  2949. var responseToReport = upload.normalizeResponse(response, false), inProgressIdx;
  2950. if (responseToReport.reset) {
  2951. chunked.reset(id);
  2952. } else {
  2953. inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx);
  2954. if (inProgressIdx >= 0) {
  2955. handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1);
  2956. handler._getFileState(id).chunking.remaining.unshift(chunkIdx);
  2957. }
  2958. }
  2959. if (!handler._getFileState(id).temp.ignoreFailure) {
  2960. if (concurrentChunkingPossible) {
  2961. handler._getFileState(id).temp.ignoreFailure = true;
  2962. log(qq.format("Going to attempt to abort these chunks: {}. These are currently in-progress: {}.", JSON.stringify(Object.keys(handler._getXhrs(id))), JSON.stringify(handler._getFileState(id).chunking.inProgress)));
  2963. qq.each(handler._getXhrs(id), function(ckid, ckXhr) {
  2964. log(qq.format("Attempting to abort file {}.{}. XHR readyState {}. ", id, ckid, ckXhr.readyState));
  2965. ckXhr.abort();
  2966. ckXhr._cancelled = true;
  2967. });
  2968. handler.moveInProgressToRemaining(id);
  2969. connectionManager.free(id, true);
  2970. }
  2971. if (!options.onAutoRetry(id, name, responseToReport, xhr)) {
  2972. upload.cleanup(id, responseToReport, xhr);
  2973. }
  2974. }
  2975. },
  2976. hasMoreParts: function(id) {
  2977. return !!handler._getFileState(id).chunking.remaining.length;
  2978. },
  2979. nextPart: function(id) {
  2980. var nextIdx = handler._getFileState(id).chunking.remaining.shift();
  2981. if (nextIdx >= handler._getTotalChunks(id)) {
  2982. nextIdx = null;
  2983. }
  2984. return nextIdx;
  2985. },
  2986. reset: function(id) {
  2987. log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error");
  2988. handler._maybeDeletePersistedChunkData(id);
  2989. handler.reevaluateChunking(id);
  2990. handler._getFileState(id).loaded = 0;
  2991. },
  2992. sendNext: function(id) {
  2993. var size = options.getSize(id), name = options.getName(id), chunkIdx = chunked.nextPart(id), chunkData = handler._getChunkData(id, chunkIdx), resuming = handler._getFileState(id).attemptingResume, inProgressChunks = handler._getFileState(id).chunking.inProgress || [];
  2994. if (handler._getFileState(id).loaded == null) {
  2995. handler._getFileState(id).loaded = 0;
  2996. }
  2997. if (resuming && options.onResume(id, name, chunkData) === false) {
  2998. chunked.reset(id);
  2999. chunkIdx = chunked.nextPart(id);
  3000. chunkData = handler._getChunkData(id, chunkIdx);
  3001. resuming = false;
  3002. }
  3003. if (chunkIdx == null && inProgressChunks.length === 0) {
  3004. chunked.finalize(id);
  3005. } else {
  3006. log(qq.format("Sending chunked upload request for item {}.{}, bytes {}-{} of {}.", id, chunkIdx, chunkData.start + 1, chunkData.end, size));
  3007. options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData));
  3008. inProgressChunks.push(chunkIdx);
  3009. handler._getFileState(id).chunking.inProgress = inProgressChunks;
  3010. if (concurrentChunkingPossible) {
  3011. connectionManager.open(id, chunkIdx);
  3012. }
  3013. if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) {
  3014. chunked.sendNext(id);
  3015. }
  3016. if (chunkData.blob.size === 0) {
  3017. log(qq.format("Chunk {} for file {} will not be uploaded, zero sized chunk.", chunkIdx, id), "error");
  3018. chunked.handleFailure(chunkIdx, id, "File is no longer available", null);
  3019. } else {
  3020. handler.uploadChunk(id, chunkIdx, resuming).then(function success(response, xhr) {
  3021. log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx);
  3022. handler.clearCachedChunk(id, chunkIdx);
  3023. var inProgressChunks = handler._getFileState(id).chunking.inProgress || [], responseToReport = upload.normalizeResponse(response, true), inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx);
  3024. log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id));
  3025. chunked.done(id, chunkIdx, responseToReport, xhr);
  3026. if (inProgressChunkIdx >= 0) {
  3027. inProgressChunks.splice(inProgressChunkIdx, 1);
  3028. }
  3029. handler._maybePersistChunkedState(id);
  3030. if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) {
  3031. chunked.finalize(id);
  3032. } else if (chunked.hasMoreParts(id)) {
  3033. chunked.sendNext(id);
  3034. } else {
  3035. log(qq.format("File ID {} has no more chunks to send and these chunk indexes are still marked as in-progress: {}", id, JSON.stringify(inProgressChunks)));
  3036. }
  3037. }, function failure(response, xhr) {
  3038. chunked.handleFailure(chunkIdx, id, response, xhr);
  3039. }).done(function() {
  3040. handler.clearXhr(id, chunkIdx);
  3041. });
  3042. }
  3043. }
  3044. }
  3045. }, connectionManager = {
  3046. _open: [],
  3047. _openChunks: {},
  3048. _waiting: [],
  3049. available: function() {
  3050. var max = options.maxConnections, openChunkEntriesCount = 0, openChunksCount = 0;
  3051. qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) {
  3052. openChunkEntriesCount++;
  3053. openChunksCount += openChunkIndexes.length;
  3054. });
  3055. return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount);
  3056. },
  3057. free: function(id, dontAllowNext) {
  3058. var allowNext = !dontAllowNext, waitingIndex = qq.indexOf(connectionManager._waiting, id), connectionsIndex = qq.indexOf(connectionManager._open, id), nextId;
  3059. delete connectionManager._openChunks[id];
  3060. if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) {
  3061. log("Generated blob upload has ended for " + id + ", disposing generated blob.");
  3062. delete handler._getFileState(id).file;
  3063. }
  3064. if (waitingIndex >= 0) {
  3065. connectionManager._waiting.splice(waitingIndex, 1);
  3066. } else if (allowNext && connectionsIndex >= 0) {
  3067. connectionManager._open.splice(connectionsIndex, 1);
  3068. nextId = connectionManager._waiting.shift();
  3069. if (nextId >= 0) {
  3070. connectionManager._open.push(nextId);
  3071. upload.start(nextId);
  3072. }
  3073. }
  3074. },
  3075. getWaitingOrConnected: function() {
  3076. var waitingOrConnected = [];
  3077. qq.each(connectionManager._openChunks, function(fileId, chunks) {
  3078. if (chunks && chunks.length) {
  3079. waitingOrConnected.push(parseInt(fileId));
  3080. }
  3081. });
  3082. qq.each(connectionManager._open, function(idx, fileId) {
  3083. if (!connectionManager._openChunks[fileId]) {
  3084. waitingOrConnected.push(parseInt(fileId));
  3085. }
  3086. });
  3087. waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting);
  3088. return waitingOrConnected;
  3089. },
  3090. isUsingConnection: function(id) {
  3091. return qq.indexOf(connectionManager._open, id) >= 0;
  3092. },
  3093. open: function(id, chunkIdx) {
  3094. if (chunkIdx == null) {
  3095. connectionManager._waiting.push(id);
  3096. }
  3097. if (connectionManager.available()) {
  3098. if (chunkIdx == null) {
  3099. connectionManager._waiting.pop();
  3100. connectionManager._open.push(id);
  3101. } else {
  3102. (function() {
  3103. var openChunksEntry = connectionManager._openChunks[id] || [];
  3104. openChunksEntry.push(chunkIdx);
  3105. connectionManager._openChunks[id] = openChunksEntry;
  3106. })();
  3107. }
  3108. return true;
  3109. }
  3110. return false;
  3111. },
  3112. reset: function() {
  3113. connectionManager._waiting = [];
  3114. connectionManager._open = [];
  3115. }
  3116. }, simple = {
  3117. send: function(id, name) {
  3118. handler._getFileState(id).loaded = 0;
  3119. log("Sending simple upload request for " + id);
  3120. handler.uploadFile(id).then(function(response, optXhr) {
  3121. log("Simple upload request succeeded for " + id);
  3122. var responseToReport = upload.normalizeResponse(response, true), size = options.getSize(id);
  3123. options.onProgress(id, name, size, size);
  3124. upload.maybeNewUuid(id, responseToReport);
  3125. upload.cleanup(id, responseToReport, optXhr);
  3126. }, function(response, optXhr) {
  3127. log("Simple upload request failed for " + id);
  3128. var responseToReport = upload.normalizeResponse(response, false);
  3129. if (!options.onAutoRetry(id, name, responseToReport, optXhr)) {
  3130. upload.cleanup(id, responseToReport, optXhr);
  3131. }
  3132. });
  3133. }
  3134. }, upload = {
  3135. cancel: function(id) {
  3136. log("Cancelling " + id);
  3137. options.paramsStore.remove(id);
  3138. connectionManager.free(id);
  3139. },
  3140. cleanup: function(id, response, optXhr) {
  3141. var name = options.getName(id);
  3142. options.onComplete(id, name, response, optXhr);
  3143. if (handler._getFileState(id)) {
  3144. handler._clearXhrs && handler._clearXhrs(id);
  3145. }
  3146. connectionManager.free(id);
  3147. },
  3148. getProxyOrBlob: function(id) {
  3149. return handler.getProxy && handler.getProxy(id) || handler.getFile && handler.getFile(id);
  3150. },
  3151. initHandler: function() {
  3152. var handlerType = namespace ? qq[namespace] : qq.traditional, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form";
  3153. handler = new handlerType[handlerModuleSubtype + "UploadHandler"](options, {
  3154. getDataByUuid: options.getDataByUuid,
  3155. getName: options.getName,
  3156. getSize: options.getSize,
  3157. getUuid: options.getUuid,
  3158. log: log,
  3159. onCancel: options.onCancel,
  3160. onProgress: options.onProgress,
  3161. onUuidChanged: options.onUuidChanged
  3162. });
  3163. if (handler._removeExpiredChunkingRecords) {
  3164. handler._removeExpiredChunkingRecords();
  3165. }
  3166. },
  3167. isDeferredEligibleForUpload: function(id) {
  3168. return options.isQueued(id);
  3169. },
  3170. maybeDefer: function(id, blob) {
  3171. if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) {
  3172. options.onUploadPrep(id);
  3173. log("Attempting to generate a blob on-demand for " + id);
  3174. blob.create().then(function(generatedBlob) {
  3175. log("Generated an on-demand blob for " + id);
  3176. handler.updateBlob(id, generatedBlob);
  3177. options.setSize(id, generatedBlob.size);
  3178. handler.reevaluateChunking(id);
  3179. upload.maybeSendDeferredFiles(id);
  3180. }, function(errorMessage) {
  3181. var errorResponse = {};
  3182. if (errorMessage) {
  3183. errorResponse.error = errorMessage;
  3184. }
  3185. log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error");
  3186. options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null);
  3187. upload.maybeSendDeferredFiles(id);
  3188. connectionManager.free(id);
  3189. });
  3190. } else {
  3191. return upload.maybeSendDeferredFiles(id);
  3192. }
  3193. return false;
  3194. },
  3195. maybeSendDeferredFiles: function(id) {
  3196. var idsInGroup = options.getIdsInProxyGroup(id), uploadedThisId = false;
  3197. if (idsInGroup && idsInGroup.length) {
  3198. log("Maybe ready to upload proxy group file " + id);
  3199. qq.each(idsInGroup, function(idx, idInGroup) {
  3200. if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) {
  3201. uploadedThisId = idInGroup === id;
  3202. upload.now(idInGroup);
  3203. } else if (upload.isDeferredEligibleForUpload(idInGroup)) {
  3204. return false;
  3205. }
  3206. });
  3207. } else {
  3208. uploadedThisId = true;
  3209. upload.now(id);
  3210. }
  3211. return uploadedThisId;
  3212. },
  3213. maybeNewUuid: function(id, response) {
  3214. if (response.newUuid !== undefined) {
  3215. options.onUuidChanged(id, response.newUuid);
  3216. }
  3217. },
  3218. normalizeResponse: function(originalResponse, successful) {
  3219. var response = originalResponse;
  3220. if (!qq.isObject(originalResponse)) {
  3221. response = {};
  3222. if (qq.isString(originalResponse) && !successful) {
  3223. response.error = originalResponse;
  3224. }
  3225. }
  3226. response.success = successful;
  3227. return response;
  3228. },
  3229. now: function(id) {
  3230. var name = options.getName(id);
  3231. if (!controller.isValid(id)) {
  3232. throw new qq.Error(id + " is not a valid file ID to upload!");
  3233. }
  3234. options.onUpload(id, name);
  3235. if (chunkingPossible && handler._shouldChunkThisFile(id)) {
  3236. chunked.sendNext(id);
  3237. } else {
  3238. simple.send(id, name);
  3239. }
  3240. },
  3241. start: function(id) {
  3242. var blobToUpload = upload.getProxyOrBlob(id);
  3243. if (blobToUpload) {
  3244. return upload.maybeDefer(id, blobToUpload);
  3245. } else {
  3246. upload.now(id);
  3247. return true;
  3248. }
  3249. }
  3250. };
  3251. qq.extend(this, {
  3252. add: function(id, file) {
  3253. handler.add.apply(this, arguments);
  3254. },
  3255. upload: function(id) {
  3256. if (connectionManager.open(id)) {
  3257. return upload.start(id);
  3258. }
  3259. return false;
  3260. },
  3261. retry: function(id) {
  3262. if (concurrentChunkingPossible) {
  3263. handler._getFileState(id).temp.ignoreFailure = false;
  3264. }
  3265. if (connectionManager.isUsingConnection(id)) {
  3266. return upload.start(id);
  3267. } else {
  3268. return controller.upload(id);
  3269. }
  3270. },
  3271. cancel: function(id) {
  3272. var cancelRetVal = handler.cancel(id);
  3273. if (qq.isGenericPromise(cancelRetVal)) {
  3274. cancelRetVal.then(function() {
  3275. upload.cancel(id);
  3276. });
  3277. } else if (cancelRetVal !== false) {
  3278. upload.cancel(id);
  3279. }
  3280. },
  3281. cancelAll: function() {
  3282. var waitingOrConnected = connectionManager.getWaitingOrConnected(), i;
  3283. if (waitingOrConnected.length) {
  3284. for (i = waitingOrConnected.length - 1; i >= 0; i--) {
  3285. controller.cancel(waitingOrConnected[i]);
  3286. }
  3287. }
  3288. connectionManager.reset();
  3289. },
  3290. getFile: function(id) {
  3291. if (handler.getProxy && handler.getProxy(id)) {
  3292. return handler.getProxy(id).referenceBlob;
  3293. }
  3294. return handler.getFile && handler.getFile(id);
  3295. },
  3296. isProxied: function(id) {
  3297. return !!(handler.getProxy && handler.getProxy(id));
  3298. },
  3299. getInput: function(id) {
  3300. if (handler.getInput) {
  3301. return handler.getInput(id);
  3302. }
  3303. },
  3304. reset: function() {
  3305. log("Resetting upload handler");
  3306. controller.cancelAll();
  3307. connectionManager.reset();
  3308. handler.reset();
  3309. },
  3310. expunge: function(id) {
  3311. if (controller.isValid(id)) {
  3312. return handler.expunge(id);
  3313. }
  3314. },
  3315. isValid: function(id) {
  3316. return handler.isValid(id);
  3317. },
  3318. getResumableFilesData: function() {
  3319. if (handler.getResumableFilesData) {
  3320. return handler.getResumableFilesData();
  3321. }
  3322. return [];
  3323. },
  3324. getThirdPartyFileId: function(id) {
  3325. if (controller.isValid(id)) {
  3326. return handler.getThirdPartyFileId(id);
  3327. }
  3328. },
  3329. pause: function(id) {
  3330. if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) {
  3331. connectionManager.free(id);
  3332. handler.moveInProgressToRemaining(id);
  3333. return true;
  3334. }
  3335. return false;
  3336. },
  3337. isResumable: function(id) {
  3338. return !!handler.isResumable && handler.isResumable(id);
  3339. }
  3340. });
  3341. qq.extend(options, o);
  3342. log = options.log;
  3343. chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking;
  3344. concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled;
  3345. preventRetryResponse = function() {
  3346. var response = {};
  3347. response[options.preventRetryParam] = true;
  3348. return response;
  3349. }();
  3350. upload.initHandler();
  3351. };
  3352. qq.WindowReceiveMessage = function(o) {
  3353. "use strict";
  3354. var options = {
  3355. log: function(message, level) {}
  3356. }, callbackWrapperDetachers = {};
  3357. qq.extend(options, o);
  3358. qq.extend(this, {
  3359. receiveMessage: function(id, callback) {
  3360. var onMessageCallbackWrapper = function(event) {
  3361. callback(event.data);
  3362. };
  3363. if (window.postMessage) {
  3364. callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper);
  3365. } else {
  3366. log("iframe message passing not supported in this browser!", "error");
  3367. }
  3368. },
  3369. stopReceivingMessages: function(id) {
  3370. if (window.postMessage) {
  3371. var detacher = callbackWrapperDetachers[id];
  3372. if (detacher) {
  3373. detacher();
  3374. }
  3375. }
  3376. }
  3377. });
  3378. };
  3379. qq.FormUploadHandler = function(spec) {
  3380. "use strict";
  3381. var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, inputName = options.inputName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({
  3382. log: log
  3383. });
  3384. function expungeFile(id) {
  3385. delete detachLoadEvents[id];
  3386. if (isCors) {
  3387. clearTimeout(postMessageCallbackTimers[id]);
  3388. delete postMessageCallbackTimers[id];
  3389. corsMessageReceiver.stopReceivingMessages(id);
  3390. }
  3391. var iframe = document.getElementById(handler._getIframeName(id));
  3392. if (iframe) {
  3393. iframe.setAttribute("src", "javascript:false;");
  3394. qq(iframe).remove();
  3395. }
  3396. }
  3397. function getFileIdForIframeName(iframeName) {
  3398. return iframeName.split("_")[0];
  3399. }
  3400. function initIframeForUpload(name) {
  3401. var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />");
  3402. iframe.setAttribute("id", name);
  3403. iframe.style.display = "none";
  3404. document.body.appendChild(iframe);
  3405. return iframe;
  3406. }
  3407. function registerPostMessageCallback(iframe, callback) {
  3408. var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId);
  3409. onloadCallbacks[uuid] = callback;
  3410. detachLoadEvents[fileId] = qq(iframe).attach("load", function() {
  3411. if (handler.getInput(fileId)) {
  3412. log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")");
  3413. postMessageCallbackTimers[iframeName] = setTimeout(function() {
  3414. var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName;
  3415. log(errorMessage, "error");
  3416. callback({
  3417. error: errorMessage
  3418. });
  3419. }, 1e3);
  3420. }
  3421. });
  3422. corsMessageReceiver.receiveMessage(iframeName, function(message) {
  3423. log("Received the following window message: '" + message + "'");
  3424. var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(message), uuid = response.uuid, onloadCallback;
  3425. if (uuid && onloadCallbacks[uuid]) {
  3426. log("Handling response for iframe name " + iframeName);
  3427. clearTimeout(postMessageCallbackTimers[iframeName]);
  3428. delete postMessageCallbackTimers[iframeName];
  3429. handler._detachLoadEvent(iframeName);
  3430. onloadCallback = onloadCallbacks[uuid];
  3431. delete onloadCallbacks[uuid];
  3432. corsMessageReceiver.stopReceivingMessages(iframeName);
  3433. onloadCallback(response);
  3434. } else if (!uuid) {
  3435. log("'" + message + "' does not contain a UUID - ignoring.");
  3436. }
  3437. });
  3438. }
  3439. qq.extend(this, new qq.UploadHandler(spec));
  3440. qq.override(this, function(super_) {
  3441. return {
  3442. add: function(id, fileInput) {
  3443. super_.add(id, {
  3444. input: fileInput
  3445. });
  3446. fileInput.setAttribute("name", inputName);
  3447. if (fileInput.parentNode) {
  3448. qq(fileInput).remove();
  3449. }
  3450. },
  3451. expunge: function(id) {
  3452. expungeFile(id);
  3453. super_.expunge(id);
  3454. },
  3455. isValid: function(id) {
  3456. return super_.isValid(id) && handler._getFileState(id).input !== undefined;
  3457. }
  3458. };
  3459. });
  3460. qq.extend(this, {
  3461. getInput: function(id) {
  3462. return handler._getFileState(id).input;
  3463. },
  3464. _attachLoadEvent: function(iframe, callback) {
  3465. var responseDescriptor;
  3466. if (isCors) {
  3467. registerPostMessageCallback(iframe, callback);
  3468. } else {
  3469. detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() {
  3470. log("Received response for " + iframe.id);
  3471. if (!iframe.parentNode) {
  3472. return;
  3473. }
  3474. try {
  3475. if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false") {
  3476. return;
  3477. }
  3478. } catch (error) {
  3479. log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error");
  3480. responseDescriptor = {
  3481. success: false
  3482. };
  3483. }
  3484. callback(responseDescriptor);
  3485. });
  3486. }
  3487. },
  3488. _createIframe: function(id) {
  3489. var iframeName = handler._getIframeName(id);
  3490. return initIframeForUpload(iframeName);
  3491. },
  3492. _detachLoadEvent: function(id) {
  3493. if (detachLoadEvents[id] !== undefined) {
  3494. detachLoadEvents[id]();
  3495. delete detachLoadEvents[id];
  3496. }
  3497. },
  3498. _getIframeName: function(fileId) {
  3499. return fileId + "_" + formHandlerInstanceId;
  3500. },
  3501. _initFormForUpload: function(spec) {
  3502. var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint;
  3503. if (paramsInBody) {
  3504. qq.obj2Inputs(params, form);
  3505. } else {
  3506. url = qq.obj2url(params, endpoint);
  3507. }
  3508. form.setAttribute("action", url);
  3509. form.setAttribute("target", targetName);
  3510. form.style.display = "none";
  3511. document.body.appendChild(form);
  3512. return form;
  3513. },
  3514. _parseJsonResponse: function(innerHtmlOrMessage) {
  3515. var response = {};
  3516. try {
  3517. response = qq.parseJson(innerHtmlOrMessage);
  3518. } catch (error) {
  3519. log("Error when attempting to parse iframe upload response (" + error.message + ")", "error");
  3520. }
  3521. return response;
  3522. }
  3523. });
  3524. };
  3525. qq.XhrUploadHandler = function(spec) {
  3526. "use strict";
  3527. var handler = this, namespace = spec.options.namespace, proxy = spec.proxy, chunking = spec.options.chunking, resume = spec.options.resume, chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume, getName = proxy.getName, getSize = proxy.getSize, getUuid = proxy.getUuid, getEndpoint = proxy.getEndpoint, getDataByUuid = proxy.getDataByUuid, onUuidChanged = proxy.onUuidChanged, onProgress = proxy.onProgress, log = proxy.log;
  3528. function abort(id) {
  3529. qq.each(handler._getXhrs(id), function(xhrId, xhr) {
  3530. var ajaxRequester = handler._getAjaxRequester(id, xhrId);
  3531. xhr.onreadystatechange = null;
  3532. xhr.upload.onprogress = null;
  3533. xhr.abort();
  3534. ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id);
  3535. });
  3536. }
  3537. qq.extend(this, new qq.UploadHandler(spec));
  3538. qq.override(this, function(super_) {
  3539. return {
  3540. add: function(id, blobOrProxy) {
  3541. if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) {
  3542. super_.add(id, {
  3543. file: blobOrProxy
  3544. });
  3545. } else if (blobOrProxy instanceof qq.BlobProxy) {
  3546. super_.add(id, {
  3547. proxy: blobOrProxy
  3548. });
  3549. } else {
  3550. throw new Error("Passed obj is not a File, Blob, or proxy");
  3551. }
  3552. handler._initTempState(id);
  3553. resumeEnabled && handler._maybePrepareForResume(id);
  3554. },
  3555. expunge: function(id) {
  3556. abort(id);
  3557. handler._maybeDeletePersistedChunkData(id);
  3558. handler._clearXhrs(id);
  3559. super_.expunge(id);
  3560. }
  3561. };
  3562. });
  3563. qq.extend(this, {
  3564. clearCachedChunk: function(id, chunkIdx) {
  3565. delete handler._getFileState(id).temp.cachedChunks[chunkIdx];
  3566. },
  3567. clearXhr: function(id, chunkIdx) {
  3568. var tempState = handler._getFileState(id).temp;
  3569. if (tempState.xhrs) {
  3570. delete tempState.xhrs[chunkIdx];
  3571. }
  3572. if (tempState.ajaxRequesters) {
  3573. delete tempState.ajaxRequesters[chunkIdx];
  3574. }
  3575. },
  3576. finalizeChunks: function(id, responseParser) {
  3577. var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx);
  3578. if (responseParser) {
  3579. return new qq.Promise().success(responseParser(xhr), xhr);
  3580. }
  3581. return new qq.Promise().success({}, xhr);
  3582. },
  3583. getFile: function(id) {
  3584. return handler.isValid(id) && handler._getFileState(id).file;
  3585. },
  3586. getProxy: function(id) {
  3587. return handler.isValid(id) && handler._getFileState(id).proxy;
  3588. },
  3589. getResumableFilesData: function() {
  3590. var resumableFilesData = [];
  3591. handler._iterateResumeRecords(function(key, uploadData) {
  3592. handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining);
  3593. var data = {
  3594. name: uploadData.name,
  3595. remaining: uploadData.chunking.remaining,
  3596. size: uploadData.size,
  3597. uuid: uploadData.uuid
  3598. };
  3599. if (uploadData.key) {
  3600. data.key = uploadData.key;
  3601. }
  3602. resumableFilesData.push(data);
  3603. });
  3604. return resumableFilesData;
  3605. },
  3606. isResumable: function(id) {
  3607. return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable;
  3608. },
  3609. moveInProgressToRemaining: function(id, optInProgress, optRemaining) {
  3610. var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress, remaining = optRemaining || handler._getFileState(id).chunking.remaining;
  3611. if (inProgress) {
  3612. log(qq.format("Moving these chunks from in-progress {}, to remaining.", JSON.stringify(inProgress)));
  3613. inProgress.reverse();
  3614. qq.each(inProgress, function(idx, chunkIdx) {
  3615. remaining.unshift(chunkIdx);
  3616. });
  3617. inProgress.length = 0;
  3618. }
  3619. },
  3620. pause: function(id) {
  3621. if (handler.isValid(id)) {
  3622. log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id)));
  3623. handler._getFileState(id).paused = true;
  3624. abort(id);
  3625. return true;
  3626. }
  3627. },
  3628. reevaluateChunking: function(id) {
  3629. if (chunking && handler.isValid(id)) {
  3630. var state = handler._getFileState(id), totalChunks, i;
  3631. delete state.chunking;
  3632. state.chunking = {};
  3633. totalChunks = handler._getTotalChunks(id);
  3634. if (totalChunks > 1 || chunking.mandatory) {
  3635. state.chunking.enabled = true;
  3636. state.chunking.parts = totalChunks;
  3637. state.chunking.remaining = [];
  3638. for (i = 0; i < totalChunks; i++) {
  3639. state.chunking.remaining.push(i);
  3640. }
  3641. handler._initTempState(id);
  3642. } else {
  3643. state.chunking.enabled = false;
  3644. }
  3645. }
  3646. },
  3647. updateBlob: function(id, newBlob) {
  3648. if (handler.isValid(id)) {
  3649. handler._getFileState(id).file = newBlob;
  3650. }
  3651. },
  3652. _clearXhrs: function(id) {
  3653. var tempState = handler._getFileState(id).temp;
  3654. qq.each(tempState.ajaxRequesters, function(chunkId) {
  3655. delete tempState.ajaxRequesters[chunkId];
  3656. });
  3657. qq.each(tempState.xhrs, function(chunkId) {
  3658. delete tempState.xhrs[chunkId];
  3659. });
  3660. },
  3661. _createXhr: function(id, optChunkIdx) {
  3662. return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance());
  3663. },
  3664. _getAjaxRequester: function(id, optChunkIdx) {
  3665. var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
  3666. return handler._getFileState(id).temp.ajaxRequesters[chunkIdx];
  3667. },
  3668. _getChunkData: function(id, chunkIndex) {
  3669. var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = handler.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize, totalChunks = handler._getTotalChunks(id), cachedChunks = this._getFileState(id).temp.cachedChunks, blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes);
  3670. cachedChunks[chunkIndex] = blob;
  3671. return {
  3672. part: chunkIndex,
  3673. start: startBytes,
  3674. end: endBytes,
  3675. count: totalChunks,
  3676. blob: blob,
  3677. size: endBytes - startBytes
  3678. };
  3679. },
  3680. _getChunkDataForCallback: function(chunkData) {
  3681. return {
  3682. partIndex: chunkData.part,
  3683. startByte: chunkData.start + 1,
  3684. endByte: chunkData.end,
  3685. totalParts: chunkData.count
  3686. };
  3687. },
  3688. _getLocalStorageId: function(id) {
  3689. var formatVersion = "5.0", name = getName(id), size = getSize(id), chunkSize = chunking.partSize, endpoint = getEndpoint(id);
  3690. return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint);
  3691. },
  3692. _getMimeType: function(id) {
  3693. return handler.getFile(id).type;
  3694. },
  3695. _getPersistableData: function(id) {
  3696. return handler._getFileState(id).chunking;
  3697. },
  3698. _getTotalChunks: function(id) {
  3699. if (chunking) {
  3700. var fileSize = getSize(id), chunkSize = chunking.partSize;
  3701. return Math.ceil(fileSize / chunkSize);
  3702. }
  3703. },
  3704. _getXhr: function(id, optChunkIdx) {
  3705. var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
  3706. return handler._getFileState(id).temp.xhrs[chunkIdx];
  3707. },
  3708. _getXhrs: function(id) {
  3709. return handler._getFileState(id).temp.xhrs;
  3710. },
  3711. _iterateResumeRecords: function(callback) {
  3712. if (resumeEnabled) {
  3713. qq.each(localStorage, function(key, item) {
  3714. if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) {
  3715. var uploadData = JSON.parse(item);
  3716. callback(key, uploadData);
  3717. }
  3718. });
  3719. }
  3720. },
  3721. _initTempState: function(id) {
  3722. handler._getFileState(id).temp = {
  3723. ajaxRequesters: {},
  3724. chunkProgress: {},
  3725. xhrs: {},
  3726. cachedChunks: {}
  3727. };
  3728. },
  3729. _markNotResumable: function(id) {
  3730. handler._getFileState(id).notResumable = true;
  3731. },
  3732. _maybeDeletePersistedChunkData: function(id) {
  3733. var localStorageId;
  3734. if (resumeEnabled && handler.isResumable(id)) {
  3735. localStorageId = handler._getLocalStorageId(id);
  3736. if (localStorageId && localStorage.getItem(localStorageId)) {
  3737. localStorage.removeItem(localStorageId);
  3738. return true;
  3739. }
  3740. }
  3741. return false;
  3742. },
  3743. _maybePrepareForResume: function(id) {
  3744. var state = handler._getFileState(id), localStorageId, persistedData;
  3745. if (resumeEnabled && state.key === undefined) {
  3746. localStorageId = handler._getLocalStorageId(id);
  3747. persistedData = localStorage.getItem(localStorageId);
  3748. if (persistedData) {
  3749. persistedData = JSON.parse(persistedData);
  3750. if (getDataByUuid(persistedData.uuid)) {
  3751. handler._markNotResumable(id);
  3752. } else {
  3753. log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id)));
  3754. onUuidChanged(id, persistedData.uuid);
  3755. state.key = persistedData.key;
  3756. state.chunking = persistedData.chunking;
  3757. state.loaded = persistedData.loaded;
  3758. state.attemptingResume = true;
  3759. handler.moveInProgressToRemaining(id);
  3760. }
  3761. }
  3762. }
  3763. },
  3764. _maybePersistChunkedState: function(id) {
  3765. var state = handler._getFileState(id), localStorageId, persistedData;
  3766. if (resumeEnabled && handler.isResumable(id)) {
  3767. localStorageId = handler._getLocalStorageId(id);
  3768. persistedData = {
  3769. name: getName(id),
  3770. size: getSize(id),
  3771. uuid: getUuid(id),
  3772. key: state.key,
  3773. chunking: state.chunking,
  3774. loaded: state.loaded,
  3775. lastUpdated: Date.now()
  3776. };
  3777. try {
  3778. localStorage.setItem(localStorageId, JSON.stringify(persistedData));
  3779. } catch (error) {
  3780. log(qq.format("Unable to save resume data for '{}' due to error: '{}'.", id, error.toString()), "warn");
  3781. }
  3782. }
  3783. },
  3784. _registerProgressHandler: function(id, chunkIdx, chunkSize) {
  3785. var xhr = handler._getXhr(id, chunkIdx), name = getName(id), progressCalculator = {
  3786. simple: function(loaded, total) {
  3787. var fileSize = getSize(id);
  3788. if (loaded === total) {
  3789. onProgress(id, name, fileSize, fileSize);
  3790. } else {
  3791. onProgress(id, name, loaded >= fileSize ? fileSize - 1 : loaded, fileSize);
  3792. }
  3793. },
  3794. chunked: function(loaded, total) {
  3795. var chunkProgress = handler._getFileState(id).temp.chunkProgress, totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded, loadedForRequest = loaded, totalForRequest = total, totalFileSize = getSize(id), estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize), totalLoadedForFile = totalSuccessfullyLoadedForFile;
  3796. chunkProgress[chunkIdx] = estActualChunkLoaded;
  3797. qq.each(chunkProgress, function(chunkIdx, chunkLoaded) {
  3798. totalLoadedForFile += chunkLoaded;
  3799. });
  3800. onProgress(id, name, totalLoadedForFile, totalFileSize);
  3801. }
  3802. };
  3803. xhr.upload.onprogress = function(e) {
  3804. if (e.lengthComputable) {
  3805. var type = chunkSize == null ? "simple" : "chunked";
  3806. progressCalculator[type](e.loaded, e.total);
  3807. }
  3808. };
  3809. },
  3810. _registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) {
  3811. var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp;
  3812. tempState.xhrs = tempState.xhrs || {};
  3813. tempState.ajaxRequesters = tempState.ajaxRequesters || {};
  3814. tempState.xhrs[xhrsId] = xhr;
  3815. if (optAjaxRequester) {
  3816. tempState.ajaxRequesters[xhrsId] = optAjaxRequester;
  3817. }
  3818. return xhr;
  3819. },
  3820. _removeExpiredChunkingRecords: function() {
  3821. var expirationDays = resume.recordsExpireIn;
  3822. handler._iterateResumeRecords(function(key, uploadData) {
  3823. var expirationDate = new Date(uploadData.lastUpdated);
  3824. expirationDate.setDate(expirationDate.getDate() + expirationDays);
  3825. if (expirationDate.getTime() <= Date.now()) {
  3826. log("Removing expired resume record with key " + key);
  3827. localStorage.removeItem(key);
  3828. }
  3829. });
  3830. },
  3831. _shouldChunkThisFile: function(id) {
  3832. var state = handler._getFileState(id);
  3833. if (!state.chunking) {
  3834. handler.reevaluateChunking(id);
  3835. }
  3836. return state.chunking.enabled;
  3837. }
  3838. });
  3839. };
  3840. qq.DeleteFileAjaxRequester = function(o) {
  3841. "use strict";
  3842. var requester, options = {
  3843. method: "DELETE",
  3844. uuidParamName: "qquuid",
  3845. endpointStore: {},
  3846. maxConnections: 3,
  3847. customHeaders: function(id) {
  3848. return {};
  3849. },
  3850. paramsStore: {},
  3851. cors: {
  3852. expected: false,
  3853. sendCredentials: false
  3854. },
  3855. log: function(str, level) {},
  3856. onDelete: function(id) {},
  3857. onDeleteComplete: function(id, xhrOrXdr, isError) {}
  3858. };
  3859. qq.extend(options, o);
  3860. function getMandatedParams() {
  3861. if (options.method.toUpperCase() === "POST") {
  3862. return {
  3863. _method: "DELETE"
  3864. };
  3865. }
  3866. return {};
  3867. }
  3868. requester = qq.extend(this, new qq.AjaxRequester({
  3869. acceptHeader: "application/json",
  3870. validMethods: [ "POST", "DELETE" ],
  3871. method: options.method,
  3872. endpointStore: options.endpointStore,
  3873. paramsStore: options.paramsStore,
  3874. mandatedParams: getMandatedParams(),
  3875. maxConnections: options.maxConnections,
  3876. customHeaders: function(id) {
  3877. return options.customHeaders.get(id);
  3878. },
  3879. log: options.log,
  3880. onSend: options.onDelete,
  3881. onComplete: options.onDeleteComplete,
  3882. cors: options.cors
  3883. }));
  3884. qq.extend(this, {
  3885. sendDelete: function(id, uuid, additionalMandatedParams) {
  3886. var additionalOptions = additionalMandatedParams || {};
  3887. options.log("Submitting delete file request for " + id);
  3888. if (options.method === "DELETE") {
  3889. requester.initTransport(id).withPath(uuid).withParams(additionalOptions).send();
  3890. } else {
  3891. additionalOptions[options.uuidParamName] = uuid;
  3892. requester.initTransport(id).withParams(additionalOptions).send();
  3893. }
  3894. }
  3895. });
  3896. };
  3897. (function() {
  3898. function detectSubsampling(img) {
  3899. var iw = img.naturalWidth, ih = img.naturalHeight, canvas = document.createElement("canvas"), ctx;
  3900. if (iw * ih > 1024 * 1024) {
  3901. canvas.width = canvas.height = 1;
  3902. ctx = canvas.getContext("2d");
  3903. ctx.drawImage(img, -iw + 1, 0);
  3904. return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
  3905. } else {
  3906. return false;
  3907. }
  3908. }
  3909. function detectVerticalSquash(img, iw, ih) {
  3910. var canvas = document.createElement("canvas"), sy = 0, ey = ih, py = ih, ctx, data, alpha, ratio;
  3911. canvas.width = 1;
  3912. canvas.height = ih;
  3913. ctx = canvas.getContext("2d");
  3914. ctx.drawImage(img, 0, 0);
  3915. data = ctx.getImageData(0, 0, 1, ih).data;
  3916. while (py > sy) {
  3917. alpha = data[(py - 1) * 4 + 3];
  3918. if (alpha === 0) {
  3919. ey = py;
  3920. } else {
  3921. sy = py;
  3922. }
  3923. py = ey + sy >> 1;
  3924. }
  3925. ratio = py / ih;
  3926. return ratio === 0 ? 1 : ratio;
  3927. }
  3928. function renderImageToDataURL(img, blob, options, doSquash) {
  3929. var canvas = document.createElement("canvas"), mime = options.mime || "image/jpeg", promise = new qq.Promise();
  3930. renderImageToCanvas(img, blob, canvas, options, doSquash).then(function() {
  3931. promise.success(canvas.toDataURL(mime, options.quality || .8));
  3932. });
  3933. return promise;
  3934. }
  3935. function maybeCalculateDownsampledDimensions(spec) {
  3936. var maxPixels = 5241e3;
  3937. if (!qq.ios()) {
  3938. throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!");
  3939. }
  3940. if (spec.origHeight * spec.origWidth > maxPixels) {
  3941. return {
  3942. newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))),
  3943. newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight)))
  3944. };
  3945. }
  3946. }
  3947. function renderImageToCanvas(img, blob, canvas, options, doSquash) {
  3948. var iw = img.naturalWidth, ih = img.naturalHeight, width = options.width, height = options.height, ctx = canvas.getContext("2d"), promise = new qq.Promise(), modifiedDimensions;
  3949. ctx.save();
  3950. if (options.resize) {
  3951. return renderImageToCanvasWithCustomResizer({
  3952. blob: blob,
  3953. canvas: canvas,
  3954. image: img,
  3955. imageHeight: ih,
  3956. imageWidth: iw,
  3957. orientation: options.orientation,
  3958. resize: options.resize,
  3959. targetHeight: height,
  3960. targetWidth: width
  3961. });
  3962. }
  3963. if (!qq.supportedFeatures.unlimitedScaledImageSize) {
  3964. modifiedDimensions = maybeCalculateDownsampledDimensions({
  3965. origWidth: width,
  3966. origHeight: height
  3967. });
  3968. if (modifiedDimensions) {
  3969. qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h", width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight), "warn");
  3970. width = modifiedDimensions.newWidth;
  3971. height = modifiedDimensions.newHeight;
  3972. }
  3973. }
  3974. transformCoordinate(canvas, width, height, options.orientation);
  3975. if (qq.ios()) {
  3976. (function() {
  3977. if (detectSubsampling(img)) {
  3978. iw /= 2;
  3979. ih /= 2;
  3980. }
  3981. var d = 1024, tmpCanvas = document.createElement("canvas"), vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1, dw = Math.ceil(d * width / iw), dh = Math.ceil(d * height / ih / vertSquashRatio), sy = 0, dy = 0, tmpCtx, sx, dx;
  3982. tmpCanvas.width = tmpCanvas.height = d;
  3983. tmpCtx = tmpCanvas.getContext("2d");
  3984. while (sy < ih) {
  3985. sx = 0;
  3986. dx = 0;
  3987. while (sx < iw) {
  3988. tmpCtx.clearRect(0, 0, d, d);
  3989. tmpCtx.drawImage(img, -sx, -sy);
  3990. ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
  3991. sx += d;
  3992. dx += dw;
  3993. }
  3994. sy += d;
  3995. dy += dh;
  3996. }
  3997. ctx.restore();
  3998. tmpCanvas = tmpCtx = null;
  3999. })();
  4000. } else {
  4001. ctx.drawImage(img, 0, 0, width, height);
  4002. }
  4003. canvas.qqImageRendered && canvas.qqImageRendered();
  4004. promise.success();
  4005. return promise;
  4006. }
  4007. function renderImageToCanvasWithCustomResizer(resizeInfo) {
  4008. var blob = resizeInfo.blob, image = resizeInfo.image, imageHeight = resizeInfo.imageHeight, imageWidth = resizeInfo.imageWidth, orientation = resizeInfo.orientation, promise = new qq.Promise(), resize = resizeInfo.resize, sourceCanvas = document.createElement("canvas"), sourceCanvasContext = sourceCanvas.getContext("2d"), targetCanvas = resizeInfo.canvas, targetHeight = resizeInfo.targetHeight, targetWidth = resizeInfo.targetWidth;
  4009. transformCoordinate(sourceCanvas, imageWidth, imageHeight, orientation);
  4010. targetCanvas.height = targetHeight;
  4011. targetCanvas.width = targetWidth;
  4012. sourceCanvasContext.drawImage(image, 0, 0);
  4013. resize({
  4014. blob: blob,
  4015. height: targetHeight,
  4016. image: image,
  4017. sourceCanvas: sourceCanvas,
  4018. targetCanvas: targetCanvas,
  4019. width: targetWidth
  4020. }).then(function success() {
  4021. targetCanvas.qqImageRendered && targetCanvas.qqImageRendered();
  4022. promise.success();
  4023. }, promise.failure);
  4024. return promise;
  4025. }
  4026. function transformCoordinate(canvas, width, height, orientation) {
  4027. switch (orientation) {
  4028. case 5:
  4029. case 6:
  4030. case 7:
  4031. case 8:
  4032. canvas.width = height;
  4033. canvas.height = width;
  4034. break;
  4035. default:
  4036. canvas.width = width;
  4037. canvas.height = height;
  4038. }
  4039. var ctx = canvas.getContext("2d");
  4040. switch (orientation) {
  4041. case 2:
  4042. ctx.translate(width, 0);
  4043. ctx.scale(-1, 1);
  4044. break;
  4045. case 3:
  4046. ctx.translate(width, height);
  4047. ctx.rotate(Math.PI);
  4048. break;
  4049. case 4:
  4050. ctx.translate(0, height);
  4051. ctx.scale(1, -1);
  4052. break;
  4053. case 5:
  4054. ctx.rotate(.5 * Math.PI);
  4055. ctx.scale(1, -1);
  4056. break;
  4057. case 6:
  4058. ctx.rotate(.5 * Math.PI);
  4059. ctx.translate(0, -height);
  4060. break;
  4061. case 7:
  4062. ctx.rotate(.5 * Math.PI);
  4063. ctx.translate(width, -height);
  4064. ctx.scale(-1, 1);
  4065. break;
  4066. case 8:
  4067. ctx.rotate(-.5 * Math.PI);
  4068. ctx.translate(-width, 0);
  4069. break;
  4070. default:
  4071. break;
  4072. }
  4073. }
  4074. function MegaPixImage(srcImage, errorCallback) {
  4075. var self = this;
  4076. if (window.Blob && srcImage instanceof Blob) {
  4077. (function() {
  4078. var img = new Image(), URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
  4079. if (!URL) {
  4080. throw Error("No createObjectURL function found to create blob url");
  4081. }
  4082. img.src = URL.createObjectURL(srcImage);
  4083. self.blob = srcImage;
  4084. srcImage = img;
  4085. })();
  4086. }
  4087. if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
  4088. srcImage.onload = function() {
  4089. var listeners = self.imageLoadListeners;
  4090. if (listeners) {
  4091. self.imageLoadListeners = null;
  4092. setTimeout(function() {
  4093. for (var i = 0, len = listeners.length; i < len; i++) {
  4094. listeners[i]();
  4095. }
  4096. }, 0);
  4097. }
  4098. };
  4099. srcImage.onerror = errorCallback;
  4100. this.imageLoadListeners = [];
  4101. }
  4102. this.srcImage = srcImage;
  4103. }
  4104. MegaPixImage.prototype.render = function(target, options) {
  4105. options = options || {};
  4106. var self = this, imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === "image/jpeg", tagName = target.tagName.toLowerCase(), opt;
  4107. if (this.imageLoadListeners) {
  4108. this.imageLoadListeners.push(function() {
  4109. self.render(target, options);
  4110. });
  4111. return;
  4112. }
  4113. if (width && !height) {
  4114. height = imgHeight * width / imgWidth << 0;
  4115. } else if (height && !width) {
  4116. width = imgWidth * height / imgHeight << 0;
  4117. } else {
  4118. width = imgWidth;
  4119. height = imgHeight;
  4120. }
  4121. if (maxWidth && width > maxWidth) {
  4122. width = maxWidth;
  4123. height = imgHeight * width / imgWidth << 0;
  4124. }
  4125. if (maxHeight && height > maxHeight) {
  4126. height = maxHeight;
  4127. width = imgWidth * height / imgHeight << 0;
  4128. }
  4129. opt = {
  4130. width: width,
  4131. height: height
  4132. }, qq.each(options, function(optionsKey, optionsValue) {
  4133. opt[optionsKey] = optionsValue;
  4134. });
  4135. if (tagName === "img") {
  4136. (function() {
  4137. var oldTargetSrc = target.src;
  4138. renderImageToDataURL(self.srcImage, self.blob, opt, doSquash).then(function(dataUri) {
  4139. target.src = dataUri;
  4140. oldTargetSrc === target.src && target.onload();
  4141. });
  4142. })();
  4143. } else if (tagName === "canvas") {
  4144. renderImageToCanvas(this.srcImage, this.blob, target, opt, doSquash);
  4145. }
  4146. if (typeof this.onrender === "function") {
  4147. this.onrender(target);
  4148. }
  4149. };
  4150. qq.MegaPixImage = MegaPixImage;
  4151. })();
  4152. qq.ImageGenerator = function(log) {
  4153. "use strict";
  4154. function isImg(el) {
  4155. return el.tagName.toLowerCase() === "img";
  4156. }
  4157. function isCanvas(el) {
  4158. return el.tagName.toLowerCase() === "canvas";
  4159. }
  4160. function isImgCorsSupported() {
  4161. return new Image().crossOrigin !== undefined;
  4162. }
  4163. function isCanvasSupported() {
  4164. var canvas = document.createElement("canvas");
  4165. return canvas.getContext && canvas.getContext("2d");
  4166. }
  4167. function determineMimeOfFileName(nameWithPath) {
  4168. var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1].split("?")[0], extension = qq.getExtension(name);
  4169. extension = extension && extension.toLowerCase();
  4170. switch (extension) {
  4171. case "jpeg":
  4172. case "jpg":
  4173. return "image/jpeg";
  4174. case "png":
  4175. return "image/png";
  4176. case "bmp":
  4177. return "image/bmp";
  4178. case "gif":
  4179. return "image/gif";
  4180. case "tiff":
  4181. case "tif":
  4182. return "image/tiff";
  4183. }
  4184. }
  4185. function isCrossOrigin(url) {
  4186. var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort;
  4187. targetAnchor.href = url;
  4188. targetProtocol = targetAnchor.protocol;
  4189. targetPort = targetAnchor.port;
  4190. targetHostname = targetAnchor.hostname;
  4191. if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) {
  4192. return true;
  4193. }
  4194. if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) {
  4195. return true;
  4196. }
  4197. if (targetPort !== window.location.port && !qq.ie()) {
  4198. return true;
  4199. }
  4200. return false;
  4201. }
  4202. function registerImgLoadListeners(img, promise) {
  4203. img.onload = function() {
  4204. img.onload = null;
  4205. img.onerror = null;
  4206. promise.success(img);
  4207. };
  4208. img.onerror = function() {
  4209. img.onload = null;
  4210. img.onerror = null;
  4211. log("Problem drawing thumbnail!", "error");
  4212. promise.failure(img, "Problem drawing thumbnail!");
  4213. };
  4214. }
  4215. function registerCanvasDrawImageListener(canvas, promise) {
  4216. canvas.qqImageRendered = function() {
  4217. promise.success(canvas);
  4218. };
  4219. }
  4220. function registerThumbnailRenderedListener(imgOrCanvas, promise) {
  4221. var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas);
  4222. if (isImg(imgOrCanvas)) {
  4223. registerImgLoadListeners(imgOrCanvas, promise);
  4224. } else if (isCanvas(imgOrCanvas)) {
  4225. registerCanvasDrawImageListener(imgOrCanvas, promise);
  4226. } else {
  4227. promise.failure(imgOrCanvas);
  4228. log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error");
  4229. }
  4230. return registered;
  4231. }
  4232. function draw(fileOrBlob, container, options) {
  4233. var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, orient = options.orient == null ? true : options.orient, megapixErrorHandler = function() {
  4234. container.onerror = null;
  4235. container.onload = null;
  4236. log("Could not render preview, file may be too large!", "error");
  4237. drawPreview.failure(container, "Browser cannot render image!");
  4238. };
  4239. identifier.isPreviewable().then(function(mime) {
  4240. var dummyExif = {
  4241. parse: function() {
  4242. return new qq.Promise().success();
  4243. }
  4244. }, exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif, mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler);
  4245. if (registerThumbnailRenderedListener(container, drawPreview)) {
  4246. exif.parse().then(function(exif) {
  4247. var orientation = exif && exif.Orientation;
  4248. mpImg.render(container, {
  4249. maxWidth: maxSize,
  4250. maxHeight: maxSize,
  4251. orientation: orientation,
  4252. mime: mime,
  4253. resize: options.customResizeFunction
  4254. });
  4255. }, function(failureMsg) {
  4256. log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg));
  4257. mpImg.render(container, {
  4258. maxWidth: maxSize,
  4259. maxHeight: maxSize,
  4260. mime: mime,
  4261. resize: options.customResizeFunction
  4262. });
  4263. });
  4264. }
  4265. }, function() {
  4266. log("Not previewable");
  4267. drawPreview.failure(container, "Not previewable");
  4268. });
  4269. return drawPreview;
  4270. }
  4271. function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize, customResizeFunction) {
  4272. var tempImg = new Image(), tempImgRender = new qq.Promise();
  4273. registerThumbnailRenderedListener(tempImg, tempImgRender);
  4274. if (isCrossOrigin(url)) {
  4275. tempImg.crossOrigin = "anonymous";
  4276. }
  4277. tempImg.src = url;
  4278. tempImgRender.then(function rendered() {
  4279. registerThumbnailRenderedListener(canvasOrImg, draw);
  4280. var mpImg = new qq.MegaPixImage(tempImg);
  4281. mpImg.render(canvasOrImg, {
  4282. maxWidth: maxSize,
  4283. maxHeight: maxSize,
  4284. mime: determineMimeOfFileName(url),
  4285. resize: customResizeFunction
  4286. });
  4287. }, draw.failure);
  4288. }
  4289. function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) {
  4290. registerThumbnailRenderedListener(img, draw);
  4291. qq(img).css({
  4292. maxWidth: maxSize + "px",
  4293. maxHeight: maxSize + "px"
  4294. });
  4295. img.src = url;
  4296. }
  4297. function drawFromUrl(url, container, options) {
  4298. var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null;
  4299. if (scale && isImg(container)) {
  4300. if (isCanvasSupported()) {
  4301. if (isCrossOrigin(url) && !isImgCorsSupported()) {
  4302. drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
  4303. } else {
  4304. drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
  4305. }
  4306. } else {
  4307. drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
  4308. }
  4309. } else if (isCanvas(container)) {
  4310. drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
  4311. } else if (registerThumbnailRenderedListener(container, draw)) {
  4312. container.src = url;
  4313. }
  4314. return draw;
  4315. }
  4316. qq.extend(this, {
  4317. generate: function(fileBlobOrUrl, container, options) {
  4318. if (qq.isString(fileBlobOrUrl)) {
  4319. log("Attempting to update thumbnail based on server response.");
  4320. return drawFromUrl(fileBlobOrUrl, container, options || {});
  4321. } else {
  4322. log("Attempting to draw client-side image preview.");
  4323. return draw(fileBlobOrUrl, container, options || {});
  4324. }
  4325. }
  4326. });
  4327. this._testing = {};
  4328. this._testing.isImg = isImg;
  4329. this._testing.isCanvas = isCanvas;
  4330. this._testing.isCrossOrigin = isCrossOrigin;
  4331. this._testing.determineMimeOfFileName = determineMimeOfFileName;
  4332. };
  4333. qq.Exif = function(fileOrBlob, log) {
  4334. "use strict";
  4335. var TAG_IDS = [ 274 ], TAG_INFO = {
  4336. 274: {
  4337. name: "Orientation",
  4338. bytes: 2
  4339. }
  4340. };
  4341. function parseLittleEndian(hex) {
  4342. var result = 0, pow = 0;
  4343. while (hex.length > 0) {
  4344. result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
  4345. hex = hex.substring(2, hex.length);
  4346. pow += 8;
  4347. }
  4348. return result;
  4349. }
  4350. function seekToApp1(offset, promise) {
  4351. var theOffset = offset, thePromise = promise;
  4352. if (theOffset === undefined) {
  4353. theOffset = 2;
  4354. thePromise = new qq.Promise();
  4355. }
  4356. qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) {
  4357. var match = /^ffe([0-9])/.exec(hex), segmentLength;
  4358. if (match) {
  4359. if (match[1] !== "1") {
  4360. segmentLength = parseInt(hex.slice(4, 8), 16);
  4361. seekToApp1(theOffset + segmentLength + 2, thePromise);
  4362. } else {
  4363. thePromise.success(theOffset);
  4364. }
  4365. } else {
  4366. thePromise.failure("No EXIF header to be found!");
  4367. }
  4368. });
  4369. return thePromise;
  4370. }
  4371. function getApp1Offset() {
  4372. var promise = new qq.Promise();
  4373. qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) {
  4374. if (hex.indexOf("ffd8") !== 0) {
  4375. promise.failure("Not a valid JPEG!");
  4376. } else {
  4377. seekToApp1().then(function(offset) {
  4378. promise.success(offset);
  4379. }, function(error) {
  4380. promise.failure(error);
  4381. });
  4382. }
  4383. });
  4384. return promise;
  4385. }
  4386. function isLittleEndian(app1Start) {
  4387. var promise = new qq.Promise();
  4388. qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) {
  4389. promise.success(hex === "4949");
  4390. });
  4391. return promise;
  4392. }
  4393. function getDirEntryCount(app1Start, littleEndian) {
  4394. var promise = new qq.Promise();
  4395. qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) {
  4396. if (littleEndian) {
  4397. return promise.success(parseLittleEndian(hex));
  4398. } else {
  4399. promise.success(parseInt(hex, 16));
  4400. }
  4401. });
  4402. return promise;
  4403. }
  4404. function getIfd(app1Start, dirEntries) {
  4405. var offset = app1Start + 20, bytes = dirEntries * 12;
  4406. return qq.readBlobToHex(fileOrBlob, offset, bytes);
  4407. }
  4408. function getDirEntries(ifdHex) {
  4409. var entries = [], offset = 0;
  4410. while (offset + 24 <= ifdHex.length) {
  4411. entries.push(ifdHex.slice(offset, offset + 24));
  4412. offset += 24;
  4413. }
  4414. return entries;
  4415. }
  4416. function getTagValues(littleEndian, dirEntries) {
  4417. var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {};
  4418. qq.each(dirEntries, function(idx, entry) {
  4419. var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength;
  4420. if (tagsToFindIdx >= 0) {
  4421. tagName = TAG_INFO[id].name;
  4422. tagValLength = TAG_INFO[id].bytes;
  4423. tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + tagValLength * 2);
  4424. vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16);
  4425. tagsToFind.splice(tagsToFindIdx, 1);
  4426. }
  4427. if (tagsToFind.length === 0) {
  4428. return false;
  4429. }
  4430. });
  4431. return vals;
  4432. }
  4433. qq.extend(this, {
  4434. parse: function() {
  4435. var parser = new qq.Promise(), onParseFailure = function(message) {
  4436. log(qq.format("EXIF header parse failed: '{}' ", message));
  4437. parser.failure(message);
  4438. };
  4439. getApp1Offset().then(function(app1Offset) {
  4440. log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name));
  4441. isLittleEndian(app1Offset).then(function(littleEndian) {
  4442. log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big"));
  4443. getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) {
  4444. log(qq.format("Found {} APP1 directory entries", dirEntryCount));
  4445. getIfd(app1Offset, dirEntryCount).then(function(ifdHex) {
  4446. var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries);
  4447. log("Successfully parsed some EXIF tags");
  4448. parser.success(tagValues);
  4449. }, onParseFailure);
  4450. }, onParseFailure);
  4451. }, onParseFailure);
  4452. }, onParseFailure);
  4453. return parser;
  4454. }
  4455. });
  4456. this._testing = {};
  4457. this._testing.parseLittleEndian = parseLittleEndian;
  4458. };
  4459. qq.Identify = function(fileOrBlob, log) {
  4460. "use strict";
  4461. function isIdentifiable(magicBytes, questionableBytes) {
  4462. var identifiable = false, magicBytesEntries = [].concat(magicBytes);
  4463. qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
  4464. if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
  4465. identifiable = true;
  4466. return false;
  4467. }
  4468. });
  4469. return identifiable;
  4470. }
  4471. qq.extend(this, {
  4472. isPreviewable: function() {
  4473. var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
  4474. log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
  4475. log("First pass: check type attribute of blob object.");
  4476. if (this.isPreviewableSync()) {
  4477. log("Second pass: check for magic bytes in file header.");
  4478. qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
  4479. qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
  4480. if (isIdentifiable(bytes, hex)) {
  4481. if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
  4482. previewable = true;
  4483. identifier.success(mime);
  4484. }
  4485. return false;
  4486. }
  4487. });
  4488. log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
  4489. if (!previewable) {
  4490. identifier.failure();
  4491. }
  4492. }, function() {
  4493. log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
  4494. identifier.failure();
  4495. });
  4496. } else {
  4497. identifier.failure();
  4498. }
  4499. return identifier;
  4500. },
  4501. isPreviewableSync: function() {
  4502. var fileMime = fileOrBlob.type, isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
  4503. if (isRecognizedImage) {
  4504. if (fileMime === "image/tiff") {
  4505. previewable = qq.supportedFeatures.tiffPreviews;
  4506. } else {
  4507. previewable = true;
  4508. }
  4509. }
  4510. !previewable && log(name + " is not previewable in this browser per the blob's type attr");
  4511. return previewable;
  4512. }
  4513. });
  4514. };
  4515. qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
  4516. "image/jpeg": "ffd8ff",
  4517. "image/gif": "474946",
  4518. "image/png": "89504e",
  4519. "image/bmp": "424d",
  4520. "image/tiff": [ "49492a00", "4d4d002a" ]
  4521. };
  4522. qq.ImageValidation = function(blob, log) {
  4523. "use strict";
  4524. function hasNonZeroLimits(limits) {
  4525. var atLeastOne = false;
  4526. qq.each(limits, function(limit, value) {
  4527. if (value > 0) {
  4528. atLeastOne = true;
  4529. return false;
  4530. }
  4531. });
  4532. return atLeastOne;
  4533. }
  4534. function getWidthHeight() {
  4535. var sizeDetermination = new qq.Promise();
  4536. new qq.Identify(blob, log).isPreviewable().then(function() {
  4537. var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
  4538. if (url) {
  4539. image.onerror = function() {
  4540. log("Cannot determine dimensions for image. May be too large.", "error");
  4541. sizeDetermination.failure();
  4542. };
  4543. image.onload = function() {
  4544. sizeDetermination.success({
  4545. width: this.width,
  4546. height: this.height
  4547. });
  4548. };
  4549. image.src = url.createObjectURL(blob);
  4550. } else {
  4551. log("No createObjectURL function available to generate image URL!", "error");
  4552. sizeDetermination.failure();
  4553. }
  4554. }, sizeDetermination.failure);
  4555. return sizeDetermination;
  4556. }
  4557. function getFailingLimit(limits, dimensions) {
  4558. var failingLimit;
  4559. qq.each(limits, function(limitName, limitValue) {
  4560. if (limitValue > 0) {
  4561. var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName];
  4562. switch (limitMatcher[1]) {
  4563. case "min":
  4564. if (actualValue < limitValue) {
  4565. failingLimit = limitName;
  4566. return false;
  4567. }
  4568. break;
  4569. case "max":
  4570. if (actualValue > limitValue) {
  4571. failingLimit = limitName;
  4572. return false;
  4573. }
  4574. break;
  4575. }
  4576. }
  4577. });
  4578. return failingLimit;
  4579. }
  4580. this.validate = function(limits) {
  4581. var validationEffort = new qq.Promise();
  4582. log("Attempting to validate image.");
  4583. if (hasNonZeroLimits(limits)) {
  4584. getWidthHeight().then(function(dimensions) {
  4585. var failingLimit = getFailingLimit(limits, dimensions);
  4586. if (failingLimit) {
  4587. validationEffort.failure(failingLimit);
  4588. } else {
  4589. validationEffort.success();
  4590. }
  4591. }, validationEffort.success);
  4592. } else {
  4593. validationEffort.success();
  4594. }
  4595. return validationEffort;
  4596. };
  4597. };
  4598. qq.Session = function(spec) {
  4599. "use strict";
  4600. var options = {
  4601. endpoint: null,
  4602. params: {},
  4603. customHeaders: {},
  4604. cors: {},
  4605. addFileRecord: function(sessionData) {},
  4606. log: function(message, level) {}
  4607. };
  4608. qq.extend(options, spec, true);
  4609. function isJsonResponseValid(response) {
  4610. if (qq.isArray(response)) {
  4611. return true;
  4612. }
  4613. options.log("Session response is not an array.", "error");
  4614. }
  4615. function handleFileItems(fileItems, success, xhrOrXdr, promise) {
  4616. var someItemsIgnored = false;
  4617. success = success && isJsonResponseValid(fileItems);
  4618. if (success) {
  4619. qq.each(fileItems, function(idx, fileItem) {
  4620. if (fileItem.uuid == null) {
  4621. someItemsIgnored = true;
  4622. options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error");
  4623. } else if (fileItem.name == null) {
  4624. someItemsIgnored = true;
  4625. options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error");
  4626. } else {
  4627. try {
  4628. options.addFileRecord(fileItem);
  4629. return true;
  4630. } catch (err) {
  4631. someItemsIgnored = true;
  4632. options.log(err.message, "error");
  4633. }
  4634. }
  4635. return false;
  4636. });
  4637. }
  4638. promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr);
  4639. }
  4640. this.refresh = function() {
  4641. var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) {
  4642. handleFileItems(response, success, xhrOrXdr, refreshEffort);
  4643. }, requesterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester(qq.extend(requesterOptions, {
  4644. onComplete: refreshCompleteCallback
  4645. }));
  4646. requester.queryServer();
  4647. return refreshEffort;
  4648. };
  4649. };
  4650. qq.SessionAjaxRequester = function(spec) {
  4651. "use strict";
  4652. var requester, options = {
  4653. endpoint: null,
  4654. customHeaders: {},
  4655. params: {},
  4656. cors: {
  4657. expected: false,
  4658. sendCredentials: false
  4659. },
  4660. onComplete: function(response, success, xhrOrXdr) {},
  4661. log: function(str, level) {}
  4662. };
  4663. qq.extend(options, spec);
  4664. function onComplete(id, xhrOrXdr, isError) {
  4665. var response = null;
  4666. if (xhrOrXdr.responseText != null) {
  4667. try {
  4668. response = qq.parseJson(xhrOrXdr.responseText);
  4669. } catch (err) {
  4670. options.log("Problem parsing session response: " + err.message, "error");
  4671. isError = true;
  4672. }
  4673. }
  4674. options.onComplete(response, !isError, xhrOrXdr);
  4675. }
  4676. requester = qq.extend(this, new qq.AjaxRequester({
  4677. acceptHeader: "application/json",
  4678. validMethods: [ "GET" ],
  4679. method: "GET",
  4680. endpointStore: {
  4681. get: function() {
  4682. return options.endpoint;
  4683. }
  4684. },
  4685. customHeaders: options.customHeaders,
  4686. log: options.log,
  4687. onComplete: onComplete,
  4688. cors: options.cors
  4689. }));
  4690. qq.extend(this, {
  4691. queryServer: function() {
  4692. var params = qq.extend({}, options.params);
  4693. options.log("Session query request.");
  4694. requester.initTransport("sessionRefresh").withParams(params).withCacheBuster().send();
  4695. }
  4696. });
  4697. };
  4698. qq.Scaler = function(spec, log) {
  4699. "use strict";
  4700. var self = this, customResizeFunction = spec.customResizer, includeOriginal = spec.sendOriginal, orient = spec.orient, defaultType = spec.defaultType, defaultQuality = spec.defaultQuality / 100, failedToScaleText = spec.failureText, includeExif = spec.includeExif, sizes = this._getSortedSizes(spec.sizes);
  4701. qq.extend(this, {
  4702. enabled: qq.supportedFeatures.scaling && sizes.length > 0,
  4703. getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
  4704. var self = this, records = [], originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData, identifier = new qq.Identify(originalBlob, log);
  4705. if (identifier.isPreviewableSync()) {
  4706. qq.each(sizes, function(idx, sizeRecord) {
  4707. var outputType = self._determineOutputType({
  4708. defaultType: defaultType,
  4709. requestedType: sizeRecord.type,
  4710. refType: originalBlob.type
  4711. });
  4712. records.push({
  4713. uuid: qq.getUniqueId(),
  4714. name: self._getName(originalFileName, {
  4715. name: sizeRecord.name,
  4716. type: outputType,
  4717. refType: originalBlob.type
  4718. }),
  4719. blob: new qq.BlobProxy(originalBlob, qq.bind(self._generateScaledImage, self, {
  4720. customResizeFunction: customResizeFunction,
  4721. maxSize: sizeRecord.maxSize,
  4722. orient: orient,
  4723. type: outputType,
  4724. quality: defaultQuality,
  4725. failedText: failedToScaleText,
  4726. includeExif: includeExif,
  4727. log: log
  4728. }))
  4729. });
  4730. });
  4731. records.push({
  4732. uuid: originalFileUuid,
  4733. name: originalFileName,
  4734. size: originalBlob.size,
  4735. blob: includeOriginal ? originalBlob : null
  4736. });
  4737. } else {
  4738. records.push({
  4739. uuid: originalFileUuid,
  4740. name: originalFileName,
  4741. size: originalBlob.size,
  4742. blob: originalBlob
  4743. });
  4744. }
  4745. return records;
  4746. },
  4747. handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) {
  4748. var self = this, buttonId = file.qqButtonId || file.blob && file.blob.qqButtonId, scaledIds = [], originalId = null, addFileToHandler = api.addFileToHandler, uploadData = api.uploadData, paramsStore = api.paramsStore, proxyGroupId = qq.getUniqueId();
  4749. qq.each(self.getFileRecords(uuid, name, file), function(idx, record) {
  4750. var blobSize = record.size, id;
  4751. if (record.blob instanceof qq.BlobProxy) {
  4752. blobSize = -1;
  4753. }
  4754. id = uploadData.addFile({
  4755. uuid: record.uuid,
  4756. name: record.name,
  4757. size: blobSize,
  4758. batchId: batchId,
  4759. proxyGroupId: proxyGroupId
  4760. });
  4761. if (record.blob instanceof qq.BlobProxy) {
  4762. scaledIds.push(id);
  4763. } else {
  4764. originalId = id;
  4765. }
  4766. if (record.blob) {
  4767. addFileToHandler(id, record.blob);
  4768. fileList.push({
  4769. id: id,
  4770. file: record.blob
  4771. });
  4772. } else {
  4773. uploadData.setStatus(id, qq.status.REJECTED);
  4774. }
  4775. });
  4776. if (originalId !== null) {
  4777. qq.each(scaledIds, function(idx, scaledId) {
  4778. var params = {
  4779. qqparentuuid: uploadData.retrieve({
  4780. id: originalId
  4781. }).uuid,
  4782. qqparentsize: uploadData.retrieve({
  4783. id: originalId
  4784. }).size
  4785. };
  4786. params[uuidParamName] = uploadData.retrieve({
  4787. id: scaledId
  4788. }).uuid;
  4789. uploadData.setParentId(scaledId, originalId);
  4790. paramsStore.addReadOnly(scaledId, params);
  4791. });
  4792. if (scaledIds.length) {
  4793. (function() {
  4794. var param = {};
  4795. param[uuidParamName] = uploadData.retrieve({
  4796. id: originalId
  4797. }).uuid;
  4798. paramsStore.addReadOnly(originalId, param);
  4799. })();
  4800. }
  4801. }
  4802. }
  4803. });
  4804. };
  4805. qq.extend(qq.Scaler.prototype, {
  4806. scaleImage: function(id, specs, api) {
  4807. "use strict";
  4808. if (!qq.supportedFeatures.scaling) {
  4809. throw new qq.Error("Scaling is not supported in this browser!");
  4810. }
  4811. var scalingEffort = new qq.Promise(), log = api.log, file = api.getFile(id), uploadData = api.uploadData.retrieve({
  4812. id: id
  4813. }), name = uploadData && uploadData.name, uuid = uploadData && uploadData.uuid, scalingOptions = {
  4814. customResizer: specs.customResizer,
  4815. sendOriginal: false,
  4816. orient: specs.orient,
  4817. defaultType: specs.type || null,
  4818. defaultQuality: specs.quality,
  4819. failedToScaleText: "Unable to scale",
  4820. sizes: [ {
  4821. name: "",
  4822. maxSize: specs.maxSize
  4823. } ]
  4824. }, scaler = new qq.Scaler(scalingOptions, log);
  4825. if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) {
  4826. scalingEffort.failure();
  4827. log("Could not generate requested scaled image for " + id + ". " + "Scaling is either not possible in this browser, or the file could not be located.", "error");
  4828. } else {
  4829. qq.bind(function() {
  4830. var record = scaler.getFileRecords(uuid, name, file)[0];
  4831. if (record && record.blob instanceof qq.BlobProxy) {
  4832. record.blob.create().then(scalingEffort.success, scalingEffort.failure);
  4833. } else {
  4834. log(id + " is not a scalable image!", "error");
  4835. scalingEffort.failure();
  4836. }
  4837. }, this)();
  4838. }
  4839. return scalingEffort;
  4840. },
  4841. _determineOutputType: function(spec) {
  4842. "use strict";
  4843. var requestedType = spec.requestedType, defaultType = spec.defaultType, referenceType = spec.refType;
  4844. if (!defaultType && !requestedType) {
  4845. if (referenceType !== "image/jpeg") {
  4846. return "image/png";
  4847. }
  4848. return referenceType;
  4849. }
  4850. if (!requestedType) {
  4851. return defaultType;
  4852. }
  4853. if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
  4854. if (requestedType === "image/tiff") {
  4855. return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
  4856. }
  4857. return requestedType;
  4858. }
  4859. return defaultType;
  4860. },
  4861. _getName: function(originalName, scaledVersionProperties) {
  4862. "use strict";
  4863. var startOfExt = originalName.lastIndexOf("."), versionType = scaledVersionProperties.type || "image/png", referenceType = scaledVersionProperties.refType, scaledName = "", scaledExt = qq.getExtension(originalName), nameAppendage = "";
  4864. if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) {
  4865. nameAppendage = " (" + scaledVersionProperties.name + ")";
  4866. }
  4867. if (startOfExt >= 0) {
  4868. scaledName = originalName.substr(0, startOfExt);
  4869. if (referenceType !== versionType) {
  4870. scaledExt = versionType.split("/")[1];
  4871. }
  4872. scaledName += nameAppendage + "." + scaledExt;
  4873. } else {
  4874. scaledName = originalName + nameAppendage;
  4875. }
  4876. return scaledName;
  4877. },
  4878. _getSortedSizes: function(sizes) {
  4879. "use strict";
  4880. sizes = qq.extend([], sizes);
  4881. return sizes.sort(function(a, b) {
  4882. if (a.maxSize > b.maxSize) {
  4883. return 1;
  4884. }
  4885. if (a.maxSize < b.maxSize) {
  4886. return -1;
  4887. }
  4888. return 0;
  4889. });
  4890. },
  4891. _generateScaledImage: function(spec, sourceFile) {
  4892. "use strict";
  4893. var self = this, customResizeFunction = spec.customResizeFunction, log = spec.log, maxSize = spec.maxSize, orient = spec.orient, type = spec.type, quality = spec.quality, failedText = spec.failedText, includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg", scalingEffort = new qq.Promise(), imageGenerator = new qq.ImageGenerator(log), canvas = document.createElement("canvas");
  4894. log("Attempting to generate scaled version for " + sourceFile.name);
  4895. imageGenerator.generate(sourceFile, canvas, {
  4896. maxSize: maxSize,
  4897. orient: orient,
  4898. customResizeFunction: customResizeFunction
  4899. }).then(function() {
  4900. var scaledImageDataUri = canvas.toDataURL(type, quality), signalSuccess = function() {
  4901. log("Success generating scaled version for " + sourceFile.name);
  4902. var blob = qq.dataUriToBlob(scaledImageDataUri);
  4903. scalingEffort.success(blob);
  4904. };
  4905. if (includeExif) {
  4906. self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {
  4907. scaledImageDataUri = scaledImageDataUriWithExif;
  4908. signalSuccess();
  4909. }, function() {
  4910. log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error");
  4911. signalSuccess();
  4912. });
  4913. } else {
  4914. signalSuccess();
  4915. }
  4916. }, function() {
  4917. log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
  4918. scalingEffort.failure(failedText);
  4919. });
  4920. return scalingEffort;
  4921. },
  4922. _insertExifHeader: function(originalImage, scaledImageDataUri, log) {
  4923. "use strict";
  4924. var reader = new FileReader(), insertionEffort = new qq.Promise(), originalImageDataUri = "";
  4925. reader.onload = function() {
  4926. originalImageDataUri = reader.result;
  4927. insertionEffort.success(qq.ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));
  4928. };
  4929. reader.onerror = function() {
  4930. log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error");
  4931. insertionEffort.failure();
  4932. };
  4933. reader.readAsDataURL(originalImage);
  4934. return insertionEffort;
  4935. },
  4936. _dataUriToBlob: function(dataUri) {
  4937. "use strict";
  4938. var byteString, mimeString, arrayBuffer, intArray;
  4939. if (dataUri.split(",")[0].indexOf("base64") >= 0) {
  4940. byteString = atob(dataUri.split(",")[1]);
  4941. } else {
  4942. byteString = decodeURI(dataUri.split(",")[1]);
  4943. }
  4944. mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
  4945. arrayBuffer = new ArrayBuffer(byteString.length);
  4946. intArray = new Uint8Array(arrayBuffer);
  4947. qq.each(byteString, function(idx, character) {
  4948. intArray[idx] = character.charCodeAt(0);
  4949. });
  4950. return this._createBlob(arrayBuffer, mimeString);
  4951. },
  4952. _createBlob: function(data, mime) {
  4953. "use strict";
  4954. var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
  4955. if (blobBuilder) {
  4956. blobBuilder.append(data);
  4957. return blobBuilder.getBlob(mime);
  4958. } else {
  4959. return new Blob([ data ], {
  4960. type: mime
  4961. });
  4962. }
  4963. }
  4964. });
  4965. qq.ExifRestorer = function() {
  4966. var ExifRestorer = {};
  4967. ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
  4968. ExifRestorer.encode64 = function(input) {
  4969. var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0;
  4970. do {
  4971. chr1 = input[i++];
  4972. chr2 = input[i++];
  4973. chr3 = input[i++];
  4974. enc1 = chr1 >> 2;
  4975. enc2 = (chr1 & 3) << 4 | chr2 >> 4;
  4976. enc3 = (chr2 & 15) << 2 | chr3 >> 6;
  4977. enc4 = chr3 & 63;
  4978. if (isNaN(chr2)) {
  4979. enc3 = enc4 = 64;
  4980. } else if (isNaN(chr3)) {
  4981. enc4 = 64;
  4982. }
  4983. output = output + this.KEY_STR.charAt(enc1) + this.KEY_STR.charAt(enc2) + this.KEY_STR.charAt(enc3) + this.KEY_STR.charAt(enc4);
  4984. chr1 = chr2 = chr3 = "";
  4985. enc1 = enc2 = enc3 = enc4 = "";
  4986. } while (i < input.length);
  4987. return output;
  4988. };
  4989. ExifRestorer.restore = function(origFileBase64, resizedFileBase64) {
  4990. var expectedBase64Header = "data:image/jpeg;base64,";
  4991. if (!origFileBase64.match(expectedBase64Header)) {
  4992. return resizedFileBase64;
  4993. }
  4994. var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, ""));
  4995. var segments = this.slice2Segments(rawImage);
  4996. var image = this.exifManipulation(resizedFileBase64, segments);
  4997. return expectedBase64Header + this.encode64(image);
  4998. };
  4999. ExifRestorer.exifManipulation = function(resizedFileBase64, segments) {
  5000. var exifArray = this.getExifArray(segments), newImageArray = this.insertExif(resizedFileBase64, exifArray), aBuffer = new Uint8Array(newImageArray);
  5001. return aBuffer;
  5002. };
  5003. ExifRestorer.getExifArray = function(segments) {
  5004. var seg;
  5005. for (var x = 0; x < segments.length; x++) {
  5006. seg = segments[x];
  5007. if (seg[0] == 255 & seg[1] == 225) {
  5008. return seg;
  5009. }
  5010. }
  5011. return [];
  5012. };
  5013. ExifRestorer.insertExif = function(resizedFileBase64, exifArray) {
  5014. var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""), buf = this.decode64(imageData), separatePoint = buf.indexOf(255, 3), mae = buf.slice(0, separatePoint), ato = buf.slice(separatePoint), array = mae;
  5015. array = array.concat(exifArray);
  5016. array = array.concat(ato);
  5017. return array;
  5018. };
  5019. ExifRestorer.slice2Segments = function(rawImageArray) {
  5020. var head = 0, segments = [];
  5021. while (1) {
  5022. if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218) {
  5023. break;
  5024. }
  5025. if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216) {
  5026. head += 2;
  5027. } else {
  5028. var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3], endPoint = head + length + 2, seg = rawImageArray.slice(head, endPoint);
  5029. segments.push(seg);
  5030. head = endPoint;
  5031. }
  5032. if (head > rawImageArray.length) {
  5033. break;
  5034. }
  5035. }
  5036. return segments;
  5037. };
  5038. ExifRestorer.decode64 = function(input) {
  5039. var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0, buf = [];
  5040. var base64test = /[^A-Za-z0-9\+\/\=]/g;
  5041. if (base64test.exec(input)) {
  5042. throw new Error("There were invalid base64 characters in the input text. " + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='");
  5043. }
  5044. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  5045. do {
  5046. enc1 = this.KEY_STR.indexOf(input.charAt(i++));
  5047. enc2 = this.KEY_STR.indexOf(input.charAt(i++));
  5048. enc3 = this.KEY_STR.indexOf(input.charAt(i++));
  5049. enc4 = this.KEY_STR.indexOf(input.charAt(i++));
  5050. chr1 = enc1 << 2 | enc2 >> 4;
  5051. chr2 = (enc2 & 15) << 4 | enc3 >> 2;
  5052. chr3 = (enc3 & 3) << 6 | enc4;
  5053. buf.push(chr1);
  5054. if (enc3 != 64) {
  5055. buf.push(chr2);
  5056. }
  5057. if (enc4 != 64) {
  5058. buf.push(chr3);
  5059. }
  5060. chr1 = chr2 = chr3 = "";
  5061. enc1 = enc2 = enc3 = enc4 = "";
  5062. } while (i < input.length);
  5063. return buf;
  5064. };
  5065. return ExifRestorer;
  5066. }();
  5067. qq.TotalProgress = function(callback, getSize) {
  5068. "use strict";
  5069. var perFileProgress = {}, totalLoaded = 0, totalSize = 0, lastLoadedSent = -1, lastTotalSent = -1, callbackProxy = function(loaded, total) {
  5070. if (loaded !== lastLoadedSent || total !== lastTotalSent) {
  5071. callback(loaded, total);
  5072. }
  5073. lastLoadedSent = loaded;
  5074. lastTotalSent = total;
  5075. }, noRetryableFiles = function(failed, retryable) {
  5076. var none = true;
  5077. qq.each(failed, function(idx, failedId) {
  5078. if (qq.indexOf(retryable, failedId) >= 0) {
  5079. none = false;
  5080. return false;
  5081. }
  5082. });
  5083. return none;
  5084. }, onCancel = function(id) {
  5085. updateTotalProgress(id, -1, -1);
  5086. delete perFileProgress[id];
  5087. }, onAllComplete = function(successful, failed, retryable) {
  5088. if (failed.length === 0 || noRetryableFiles(failed, retryable)) {
  5089. callbackProxy(totalSize, totalSize);
  5090. this.reset();
  5091. }
  5092. }, onNew = function(id) {
  5093. var size = getSize(id);
  5094. if (size > 0) {
  5095. updateTotalProgress(id, 0, size);
  5096. perFileProgress[id] = {
  5097. loaded: 0,
  5098. total: size
  5099. };
  5100. }
  5101. }, updateTotalProgress = function(id, newLoaded, newTotal) {
  5102. var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0, oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0;
  5103. if (newLoaded === -1 && newTotal === -1) {
  5104. totalLoaded -= oldLoaded;
  5105. totalSize -= oldTotal;
  5106. } else {
  5107. if (newLoaded) {
  5108. totalLoaded += newLoaded - oldLoaded;
  5109. }
  5110. if (newTotal) {
  5111. totalSize += newTotal - oldTotal;
  5112. }
  5113. }
  5114. callbackProxy(totalLoaded, totalSize);
  5115. };
  5116. qq.extend(this, {
  5117. onAllComplete: onAllComplete,
  5118. onStatusChange: function(id, oldStatus, newStatus) {
  5119. if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) {
  5120. onCancel(id);
  5121. } else if (newStatus === qq.status.SUBMITTING) {
  5122. onNew(id);
  5123. }
  5124. },
  5125. onIndividualProgress: function(id, loaded, total) {
  5126. updateTotalProgress(id, loaded, total);
  5127. perFileProgress[id] = {
  5128. loaded: loaded,
  5129. total: total
  5130. };
  5131. },
  5132. onNewSize: function(id) {
  5133. onNew(id);
  5134. },
  5135. reset: function() {
  5136. perFileProgress = {};
  5137. totalLoaded = 0;
  5138. totalSize = 0;
  5139. }
  5140. });
  5141. };
  5142. qq.PasteSupport = function(o) {
  5143. "use strict";
  5144. var options, detachPasteHandler;
  5145. options = {
  5146. targetElement: null,
  5147. callbacks: {
  5148. log: function(message, level) {},
  5149. pasteReceived: function(blob) {}
  5150. }
  5151. };
  5152. function isImage(item) {
  5153. return item.type && item.type.indexOf("image/") === 0;
  5154. }
  5155. function registerPasteHandler() {
  5156. detachPasteHandler = qq(options.targetElement).attach("paste", function(event) {
  5157. var clipboardData = event.clipboardData;
  5158. if (clipboardData) {
  5159. qq.each(clipboardData.items, function(idx, item) {
  5160. if (isImage(item)) {
  5161. var blob = item.getAsFile();
  5162. options.callbacks.pasteReceived(blob);
  5163. }
  5164. });
  5165. }
  5166. });
  5167. }
  5168. function unregisterPasteHandler() {
  5169. if (detachPasteHandler) {
  5170. detachPasteHandler();
  5171. }
  5172. }
  5173. qq.extend(options, o);
  5174. registerPasteHandler();
  5175. qq.extend(this, {
  5176. reset: function() {
  5177. unregisterPasteHandler();
  5178. }
  5179. });
  5180. };
  5181. qq.FormSupport = function(options, startUpload, log) {
  5182. "use strict";
  5183. var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload;
  5184. qq.extend(this, {
  5185. newEndpoint: null,
  5186. newAutoUpload: autoUpload,
  5187. attachedToForm: false,
  5188. getFormInputsAsObject: function() {
  5189. if (formEl == null) {
  5190. return null;
  5191. }
  5192. return self._form2Obj(formEl);
  5193. }
  5194. });
  5195. function determineNewEndpoint(formEl) {
  5196. if (formEl.getAttribute("action")) {
  5197. self.newEndpoint = formEl.getAttribute("action");
  5198. }
  5199. }
  5200. function validateForm(formEl, nativeSubmit) {
  5201. if (formEl.checkValidity && !formEl.checkValidity()) {
  5202. log("Form did not pass validation checks - will not upload.", "error");
  5203. nativeSubmit();
  5204. } else {
  5205. return true;
  5206. }
  5207. }
  5208. function maybeUploadOnSubmit(formEl) {
  5209. var nativeSubmit = formEl.submit;
  5210. qq(formEl).attach("submit", function(event) {
  5211. event = event || window.event;
  5212. if (event.preventDefault) {
  5213. event.preventDefault();
  5214. } else {
  5215. event.returnValue = false;
  5216. }
  5217. validateForm(formEl, nativeSubmit) && startUpload();
  5218. });
  5219. formEl.submit = function() {
  5220. validateForm(formEl, nativeSubmit) && startUpload();
  5221. };
  5222. }
  5223. function determineFormEl(formEl) {
  5224. if (formEl) {
  5225. if (qq.isString(formEl)) {
  5226. formEl = document.getElementById(formEl);
  5227. }
  5228. if (formEl) {
  5229. log("Attaching to form element.");
  5230. determineNewEndpoint(formEl);
  5231. interceptSubmit && maybeUploadOnSubmit(formEl);
  5232. }
  5233. }
  5234. return formEl;
  5235. }
  5236. formEl = determineFormEl(formEl);
  5237. this.attachedToForm = !!formEl;
  5238. };
  5239. qq.extend(qq.FormSupport.prototype, {
  5240. _form2Obj: function(form) {
  5241. "use strict";
  5242. var obj = {}, notIrrelevantType = function(type) {
  5243. var irrelevantTypes = [ "button", "image", "reset", "submit" ];
  5244. return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0;
  5245. }, radioOrCheckbox = function(type) {
  5246. return qq.indexOf([ "checkbox", "radio" ], type.toLowerCase()) >= 0;
  5247. }, ignoreValue = function(el) {
  5248. if (radioOrCheckbox(el.type) && !el.checked) {
  5249. return true;
  5250. }
  5251. return el.disabled && el.type.toLowerCase() !== "hidden";
  5252. }, selectValue = function(select) {
  5253. var value = null;
  5254. qq.each(qq(select).children(), function(idx, child) {
  5255. if (child.tagName.toLowerCase() === "option" && child.selected) {
  5256. value = child.value;
  5257. return false;
  5258. }
  5259. });
  5260. return value;
  5261. };
  5262. qq.each(form.elements, function(idx, el) {
  5263. if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") && notIrrelevantType(el.type) && !ignoreValue(el)) {
  5264. obj[el.name] = el.value;
  5265. } else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) {
  5266. var value = selectValue(el);
  5267. if (value !== null) {
  5268. obj[el.name] = value;
  5269. }
  5270. }
  5271. });
  5272. return obj;
  5273. }
  5274. });
  5275. qq.traditional = qq.traditional || {};
  5276. qq.traditional.FormUploadHandler = function(options, proxy) {
  5277. "use strict";
  5278. var handler = this, getName = proxy.getName, getUuid = proxy.getUuid, log = proxy.log;
  5279. function getIframeContentJson(id, iframe) {
  5280. var response, doc, innerHtml;
  5281. try {
  5282. doc = iframe.contentDocument || iframe.contentWindow.document;
  5283. innerHtml = doc.body.innerHTML;
  5284. log("converting iframe's innerHTML to JSON");
  5285. log("innerHTML = " + innerHtml);
  5286. if (innerHtml && innerHtml.match(/^<pre/i)) {
  5287. innerHtml = doc.body.firstChild.firstChild.nodeValue;
  5288. }
  5289. response = handler._parseJsonResponse(innerHtml);
  5290. } catch (error) {
  5291. log("Error when attempting to parse form upload response (" + error.message + ")", "error");
  5292. response = {
  5293. success: false
  5294. };
  5295. }
  5296. return response;
  5297. }
  5298. function createForm(id, iframe) {
  5299. var params = options.paramsStore.get(id), method = options.method.toLowerCase() === "get" ? "GET" : "POST", endpoint = options.endpointStore.get(id), name = getName(id);
  5300. params[options.uuidName] = getUuid(id);
  5301. params[options.filenameParam] = name;
  5302. return handler._initFormForUpload({
  5303. method: method,
  5304. endpoint: endpoint,
  5305. params: params,
  5306. paramsInBody: options.paramsInBody,
  5307. targetName: iframe.name
  5308. });
  5309. }
  5310. this.uploadFile = function(id) {
  5311. var input = handler.getInput(id), iframe = handler._createIframe(id), promise = new qq.Promise(), form;
  5312. form = createForm(id, iframe);
  5313. form.appendChild(input);
  5314. handler._attachLoadEvent(iframe, function(responseFromMessage) {
  5315. log("iframe loaded");
  5316. var response = responseFromMessage ? responseFromMessage : getIframeContentJson(id, iframe);
  5317. handler._detachLoadEvent(id);
  5318. if (!options.cors.expected) {
  5319. qq(iframe).remove();
  5320. }
  5321. if (response.success) {
  5322. promise.success(response);
  5323. } else {
  5324. promise.failure(response);
  5325. }
  5326. });
  5327. log("Sending upload request for " + id);
  5328. form.submit();
  5329. qq(form).remove();
  5330. return promise;
  5331. };
  5332. qq.extend(this, new qq.FormUploadHandler({
  5333. options: {
  5334. isCors: options.cors.expected,
  5335. inputName: options.inputName
  5336. },
  5337. proxy: {
  5338. onCancel: options.onCancel,
  5339. getName: getName,
  5340. getUuid: getUuid,
  5341. log: log
  5342. }
  5343. }));
  5344. };
  5345. qq.traditional = qq.traditional || {};
  5346. qq.traditional.XhrUploadHandler = function(spec, proxy) {
  5347. "use strict";
  5348. var handler = this, getName = proxy.getName, getSize = proxy.getSize, getUuid = proxy.getUuid, log = proxy.log, multipart = spec.forceMultipart || spec.paramsInBody, addChunkingSpecificParams = function(id, params, chunkData) {
  5349. var size = getSize(id), name = getName(id);
  5350. params[spec.chunking.paramNames.partIndex] = chunkData.part;
  5351. params[spec.chunking.paramNames.partByteOffset] = chunkData.start;
  5352. params[spec.chunking.paramNames.chunkSize] = chunkData.size;
  5353. params[spec.chunking.paramNames.totalParts] = chunkData.count;
  5354. params[spec.totalFileSizeName] = size;
  5355. if (multipart) {
  5356. params[spec.filenameParam] = name;
  5357. }
  5358. }, allChunksDoneRequester = new qq.traditional.AllChunksDoneAjaxRequester({
  5359. cors: spec.cors,
  5360. endpoint: spec.chunking.success.endpoint,
  5361. log: log
  5362. }), createReadyStateChangedHandler = function(id, xhr) {
  5363. var promise = new qq.Promise();
  5364. xhr.onreadystatechange = function() {
  5365. if (xhr.readyState === 4) {
  5366. var result = onUploadOrChunkComplete(id, xhr);
  5367. if (result.success) {
  5368. promise.success(result.response, xhr);
  5369. } else {
  5370. promise.failure(result.response, xhr);
  5371. }
  5372. }
  5373. };
  5374. return promise;
  5375. }, getChunksCompleteParams = function(id) {
  5376. var params = spec.paramsStore.get(id), name = getName(id), size = getSize(id);
  5377. params[spec.uuidName] = getUuid(id);
  5378. params[spec.filenameParam] = name;
  5379. params[spec.totalFileSizeName] = size;
  5380. params[spec.chunking.paramNames.totalParts] = handler._getTotalChunks(id);
  5381. return params;
  5382. }, isErrorUploadResponse = function(xhr, response) {
  5383. return qq.indexOf([ 200, 201, 202, 203, 204 ], xhr.status) < 0 || !response.success || response.reset;
  5384. }, onUploadOrChunkComplete = function(id, xhr) {
  5385. var response;
  5386. log("xhr - server response received for " + id);
  5387. log("responseText = " + xhr.responseText);
  5388. response = parseResponse(true, xhr);
  5389. return {
  5390. success: !isErrorUploadResponse(xhr, response),
  5391. response: response
  5392. };
  5393. }, parseResponse = function(upload, xhr) {
  5394. var response = {};
  5395. try {
  5396. log(qq.format("Received response status {} with body: {}", xhr.status, xhr.responseText));
  5397. response = qq.parseJson(xhr.responseText);
  5398. } catch (error) {
  5399. upload && log("Error when attempting to parse xhr response text (" + error.message + ")", "error");
  5400. }
  5401. return response;
  5402. }, sendChunksCompleteRequest = function(id) {
  5403. var promise = new qq.Promise();
  5404. allChunksDoneRequester.complete(id, handler._createXhr(id), getChunksCompleteParams(id), spec.customHeaders.get(id)).then(function(xhr) {
  5405. promise.success(parseResponse(false, xhr), xhr);
  5406. }, function(xhr) {
  5407. promise.failure(parseResponse(false, xhr), xhr);
  5408. });
  5409. return promise;
  5410. }, setParamsAndGetEntityToSend = function(params, xhr, fileOrBlob, id) {
  5411. var formData = new FormData(), method = spec.method, endpoint = spec.endpointStore.get(id), name = getName(id), size = getSize(id);
  5412. params[spec.uuidName] = getUuid(id);
  5413. params[spec.filenameParam] = name;
  5414. if (multipart) {
  5415. params[spec.totalFileSizeName] = size;
  5416. }
  5417. if (!spec.paramsInBody) {
  5418. if (!multipart) {
  5419. params[spec.inputName] = name;
  5420. }
  5421. endpoint = qq.obj2url(params, endpoint);
  5422. }
  5423. xhr.open(method, endpoint, true);
  5424. if (spec.cors.expected && spec.cors.sendCredentials) {
  5425. xhr.withCredentials = true;
  5426. }
  5427. if (multipart) {
  5428. if (spec.paramsInBody) {
  5429. qq.obj2FormData(params, formData);
  5430. }
  5431. formData.append(spec.inputName, fileOrBlob);
  5432. return formData;
  5433. }
  5434. return fileOrBlob;
  5435. }, setUploadHeaders = function(id, xhr) {
  5436. var extraHeaders = spec.customHeaders.get(id), fileOrBlob = handler.getFile(id);
  5437. xhr.setRequestHeader("Accept", "application/json");
  5438. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  5439. xhr.setRequestHeader("Cache-Control", "no-cache");
  5440. if (!multipart) {
  5441. xhr.setRequestHeader("Content-Type", "application/octet-stream");
  5442. xhr.setRequestHeader("X-Mime-Type", fileOrBlob.type);
  5443. }
  5444. qq.each(extraHeaders, function(name, val) {
  5445. xhr.setRequestHeader(name, val);
  5446. });
  5447. };
  5448. qq.extend(this, {
  5449. uploadChunk: function(id, chunkIdx, resuming) {
  5450. var chunkData = handler._getChunkData(id, chunkIdx), xhr = handler._createXhr(id, chunkIdx), size = getSize(id), promise, toSend, params;
  5451. promise = createReadyStateChangedHandler(id, xhr);
  5452. handler._registerProgressHandler(id, chunkIdx, chunkData.size);
  5453. params = spec.paramsStore.get(id);
  5454. addChunkingSpecificParams(id, params, chunkData);
  5455. if (resuming) {
  5456. params[spec.resume.paramNames.resuming] = true;
  5457. }
  5458. toSend = setParamsAndGetEntityToSend(params, xhr, chunkData.blob, id);
  5459. setUploadHeaders(id, xhr);
  5460. xhr.send(toSend);
  5461. return promise;
  5462. },
  5463. uploadFile: function(id) {
  5464. var fileOrBlob = handler.getFile(id), promise, xhr, params, toSend;
  5465. xhr = handler._createXhr(id);
  5466. handler._registerProgressHandler(id);
  5467. promise = createReadyStateChangedHandler(id, xhr);
  5468. params = spec.paramsStore.get(id);
  5469. toSend = setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id);
  5470. setUploadHeaders(id, xhr);
  5471. xhr.send(toSend);
  5472. return promise;
  5473. }
  5474. });
  5475. qq.extend(this, new qq.XhrUploadHandler({
  5476. options: qq.extend({
  5477. namespace: "traditional"
  5478. }, spec),
  5479. proxy: qq.extend({
  5480. getEndpoint: spec.endpointStore.get
  5481. }, proxy)
  5482. }));
  5483. qq.override(this, function(super_) {
  5484. return {
  5485. finalizeChunks: function(id) {
  5486. if (spec.chunking.success.endpoint) {
  5487. return sendChunksCompleteRequest(id);
  5488. } else {
  5489. return super_.finalizeChunks(id, qq.bind(parseResponse, this, true));
  5490. }
  5491. }
  5492. };
  5493. });
  5494. };
  5495. qq.traditional.AllChunksDoneAjaxRequester = function(o) {
  5496. "use strict";
  5497. var requester, method = "POST", options = {
  5498. cors: {
  5499. allowXdr: false,
  5500. expected: false,
  5501. sendCredentials: false
  5502. },
  5503. endpoint: null,
  5504. log: function(str, level) {}
  5505. }, promises = {}, endpointHandler = {
  5506. get: function(id) {
  5507. return options.endpoint;
  5508. }
  5509. };
  5510. qq.extend(options, o);
  5511. requester = qq.extend(this, new qq.AjaxRequester({
  5512. acceptHeader: "application/json",
  5513. validMethods: [ method ],
  5514. method: method,
  5515. endpointStore: endpointHandler,
  5516. allowXRequestedWithAndCacheControl: false,
  5517. cors: options.cors,
  5518. log: options.log,
  5519. onComplete: function(id, xhr, isError) {
  5520. var promise = promises[id];
  5521. delete promises[id];
  5522. if (isError) {
  5523. promise.failure(xhr);
  5524. } else {
  5525. promise.success(xhr);
  5526. }
  5527. }
  5528. }));
  5529. qq.extend(this, {
  5530. complete: function(id, xhr, params, headers) {
  5531. var promise = new qq.Promise();
  5532. options.log("Submitting All Chunks Done request for " + id);
  5533. promises[id] = promise;
  5534. requester.initTransport(id).withParams(params).withHeaders(headers).send(xhr);
  5535. return promise;
  5536. }
  5537. });
  5538. };
  5539. qq.DragAndDrop = function(o) {
  5540. "use strict";
  5541. var options, HIDE_ZONES_EVENT_NAME = "qq-hidezones", HIDE_BEFORE_ENTER_ATTR = "qq-hide-dropzone", uploadDropZones = [], droppedFiles = [], disposeSupport = new qq.DisposeSupport();
  5542. options = {
  5543. dropZoneElements: [],
  5544. allowMultipleItems: true,
  5545. classes: {
  5546. dropActive: null
  5547. },
  5548. callbacks: new qq.DragAndDrop.callbacks()
  5549. };
  5550. qq.extend(options, o, true);
  5551. function uploadDroppedFiles(files, uploadDropZone) {
  5552. var filesAsArray = Array.prototype.slice.call(files);
  5553. options.callbacks.dropLog("Grabbed " + files.length + " dropped files.");
  5554. uploadDropZone.dropDisabled(false);
  5555. options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement());
  5556. }
  5557. function traverseFileTree(entry) {
  5558. var parseEntryPromise = new qq.Promise();
  5559. if (entry.isFile) {
  5560. entry.file(function(file) {
  5561. var name = entry.name, fullPath = entry.fullPath, indexOfNameInFullPath = fullPath.indexOf(name);
  5562. fullPath = fullPath.substr(0, indexOfNameInFullPath);
  5563. if (fullPath.charAt(0) === "/") {
  5564. fullPath = fullPath.substr(1);
  5565. }
  5566. file.qqPath = fullPath;
  5567. droppedFiles.push(file);
  5568. parseEntryPromise.success();
  5569. }, function(fileError) {
  5570. options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
  5571. parseEntryPromise.failure();
  5572. });
  5573. } else if (entry.isDirectory) {
  5574. getFilesInDirectory(entry).then(function allEntriesRead(entries) {
  5575. var entriesLeft = entries.length;
  5576. qq.each(entries, function(idx, entry) {
  5577. traverseFileTree(entry).done(function() {
  5578. entriesLeft -= 1;
  5579. if (entriesLeft === 0) {
  5580. parseEntryPromise.success();
  5581. }
  5582. });
  5583. });
  5584. if (!entries.length) {
  5585. parseEntryPromise.success();
  5586. }
  5587. }, function readFailure(fileError) {
  5588. options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
  5589. parseEntryPromise.failure();
  5590. });
  5591. }
  5592. return parseEntryPromise;
  5593. }
  5594. function getFilesInDirectory(entry, reader, accumEntries, existingPromise) {
  5595. var promise = existingPromise || new qq.Promise(), dirReader = reader || entry.createReader();
  5596. dirReader.readEntries(function readSuccess(entries) {
  5597. var newEntries = accumEntries ? accumEntries.concat(entries) : entries;
  5598. if (entries.length) {
  5599. setTimeout(function() {
  5600. getFilesInDirectory(entry, dirReader, newEntries, promise);
  5601. }, 0);
  5602. } else {
  5603. promise.success(newEntries);
  5604. }
  5605. }, promise.failure);
  5606. return promise;
  5607. }
  5608. function handleDataTransfer(dataTransfer, uploadDropZone) {
  5609. var pendingFolderPromises = [], handleDataTransferPromise = new qq.Promise();
  5610. options.callbacks.processingDroppedFiles();
  5611. uploadDropZone.dropDisabled(true);
  5612. if (dataTransfer.files.length > 1 && !options.allowMultipleItems) {
  5613. options.callbacks.processingDroppedFilesComplete([]);
  5614. options.callbacks.dropError("tooManyFilesError", "");
  5615. uploadDropZone.dropDisabled(false);
  5616. handleDataTransferPromise.failure();
  5617. } else {
  5618. droppedFiles = [];
  5619. if (qq.isFolderDropSupported(dataTransfer)) {
  5620. qq.each(dataTransfer.items, function(idx, item) {
  5621. var entry = item.webkitGetAsEntry();
  5622. if (entry) {
  5623. if (entry.isFile) {
  5624. droppedFiles.push(item.getAsFile());
  5625. } else {
  5626. pendingFolderPromises.push(traverseFileTree(entry).done(function() {
  5627. pendingFolderPromises.pop();
  5628. if (pendingFolderPromises.length === 0) {
  5629. handleDataTransferPromise.success();
  5630. }
  5631. }));
  5632. }
  5633. }
  5634. });
  5635. } else {
  5636. droppedFiles = dataTransfer.files;
  5637. }
  5638. if (pendingFolderPromises.length === 0) {
  5639. handleDataTransferPromise.success();
  5640. }
  5641. }
  5642. return handleDataTransferPromise;
  5643. }
  5644. function setupDropzone(dropArea) {
  5645. var dropZone = new qq.UploadDropZone({
  5646. HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME,
  5647. element: dropArea,
  5648. onEnter: function(e) {
  5649. qq(dropArea).addClass(options.classes.dropActive);
  5650. e.stopPropagation();
  5651. },
  5652. onLeaveNotDescendants: function(e) {
  5653. qq(dropArea).removeClass(options.classes.dropActive);
  5654. },
  5655. onDrop: function(e) {
  5656. handleDataTransfer(e.dataTransfer, dropZone).then(function() {
  5657. uploadDroppedFiles(droppedFiles, dropZone);
  5658. }, function() {
  5659. options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error");
  5660. });
  5661. }
  5662. });
  5663. disposeSupport.addDisposer(function() {
  5664. dropZone.dispose();
  5665. });
  5666. qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide();
  5667. uploadDropZones.push(dropZone);
  5668. return dropZone;
  5669. }
  5670. function isFileDrag(dragEvent) {
  5671. var fileDrag;
  5672. qq.each(dragEvent.dataTransfer.types, function(key, val) {
  5673. if (val === "Files") {
  5674. fileDrag = true;
  5675. return false;
  5676. }
  5677. });
  5678. return fileDrag;
  5679. }
  5680. function leavingDocumentOut(e) {
  5681. if (qq.safari()) {
  5682. return e.x < 0 || e.y < 0;
  5683. }
  5684. return e.x === 0 && e.y === 0;
  5685. }
  5686. function setupDragDrop() {
  5687. var dropZones = options.dropZoneElements, maybeHideDropZones = function() {
  5688. setTimeout(function() {
  5689. qq.each(dropZones, function(idx, dropZone) {
  5690. qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide();
  5691. qq(dropZone).removeClass(options.classes.dropActive);
  5692. });
  5693. }, 10);
  5694. };
  5695. qq.each(dropZones, function(idx, dropZone) {
  5696. var uploadDropZone = setupDropzone(dropZone);
  5697. if (dropZones.length && qq.supportedFeatures.fileDrop) {
  5698. disposeSupport.attach(document, "dragenter", function(e) {
  5699. if (!uploadDropZone.dropDisabled() && isFileDrag(e)) {
  5700. qq.each(dropZones, function(idx, dropZone) {
  5701. if (dropZone instanceof HTMLElement && qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR)) {
  5702. qq(dropZone).css({
  5703. display: "block"
  5704. });
  5705. }
  5706. });
  5707. }
  5708. });
  5709. }
  5710. });
  5711. disposeSupport.attach(document, "dragleave", function(e) {
  5712. if (leavingDocumentOut(e)) {
  5713. maybeHideDropZones();
  5714. }
  5715. });
  5716. disposeSupport.attach(qq(document).children()[0], "mouseenter", function(e) {
  5717. maybeHideDropZones();
  5718. });
  5719. disposeSupport.attach(document, "drop", function(e) {
  5720. if (isFileDrag(e)) {
  5721. e.preventDefault();
  5722. maybeHideDropZones();
  5723. }
  5724. });
  5725. disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, maybeHideDropZones);
  5726. }
  5727. setupDragDrop();
  5728. qq.extend(this, {
  5729. setupExtraDropzone: function(element) {
  5730. options.dropZoneElements.push(element);
  5731. setupDropzone(element);
  5732. },
  5733. removeDropzone: function(element) {
  5734. var i, dzs = options.dropZoneElements;
  5735. for (i in dzs) {
  5736. if (dzs[i] === element) {
  5737. return dzs.splice(i, 1);
  5738. }
  5739. }
  5740. },
  5741. dispose: function() {
  5742. disposeSupport.dispose();
  5743. qq.each(uploadDropZones, function(idx, dropZone) {
  5744. dropZone.dispose();
  5745. });
  5746. }
  5747. });
  5748. };
  5749. qq.DragAndDrop.callbacks = function() {
  5750. "use strict";
  5751. return {
  5752. processingDroppedFiles: function() {},
  5753. processingDroppedFilesComplete: function(files, targetEl) {},
  5754. dropError: function(code, errorSpecifics) {
  5755. qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error");
  5756. },
  5757. dropLog: function(message, level) {
  5758. qq.log(message, level);
  5759. }
  5760. };
  5761. };
  5762. qq.UploadDropZone = function(o) {
  5763. "use strict";
  5764. var disposeSupport = new qq.DisposeSupport(), options, element, preventDrop, dropOutsideDisabled;
  5765. options = {
  5766. element: null,
  5767. onEnter: function(e) {},
  5768. onLeave: function(e) {},
  5769. onLeaveNotDescendants: function(e) {},
  5770. onDrop: function(e) {}
  5771. };
  5772. qq.extend(options, o);
  5773. element = options.element;
  5774. function dragoverShouldBeCanceled() {
  5775. return qq.safari() || qq.firefox() && qq.windows();
  5776. }
  5777. function disableDropOutside(e) {
  5778. if (!dropOutsideDisabled) {
  5779. if (dragoverShouldBeCanceled) {
  5780. disposeSupport.attach(document, "dragover", function(e) {
  5781. e.preventDefault();
  5782. });
  5783. } else {
  5784. disposeSupport.attach(document, "dragover", function(e) {
  5785. if (e.dataTransfer) {
  5786. e.dataTransfer.dropEffect = "none";
  5787. e.preventDefault();
  5788. }
  5789. });
  5790. }
  5791. dropOutsideDisabled = true;
  5792. }
  5793. }
  5794. function isValidFileDrag(e) {
  5795. if (!qq.supportedFeatures.fileDrop) {
  5796. return false;
  5797. }
  5798. var effectTest, dt = e.dataTransfer, isSafari = qq.safari();
  5799. effectTest = qq.ie() && qq.supportedFeatures.fileDrop ? true : dt.effectAllowed !== "none";
  5800. return dt && effectTest && (dt.files && dt.files.length || !isSafari && dt.types.contains && dt.types.contains("Files") || dt.types.includes && dt.types.includes("Files"));
  5801. }
  5802. function isOrSetDropDisabled(isDisabled) {
  5803. if (isDisabled !== undefined) {
  5804. preventDrop = isDisabled;
  5805. }
  5806. return preventDrop;
  5807. }
  5808. function triggerHidezonesEvent() {
  5809. var hideZonesEvent;
  5810. function triggerUsingOldApi() {
  5811. hideZonesEvent = document.createEvent("Event");
  5812. hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true);
  5813. }
  5814. if (window.CustomEvent) {
  5815. try {
  5816. hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME);
  5817. } catch (err) {
  5818. triggerUsingOldApi();
  5819. }
  5820. } else {
  5821. triggerUsingOldApi();
  5822. }
  5823. document.dispatchEvent(hideZonesEvent);
  5824. }
  5825. function attachEvents() {
  5826. disposeSupport.attach(element, "dragover", function(e) {
  5827. if (!isValidFileDrag(e)) {
  5828. return;
  5829. }
  5830. var effect = qq.ie() && qq.supportedFeatures.fileDrop ? null : e.dataTransfer.effectAllowed;
  5831. if (effect === "move" || effect === "linkMove") {
  5832. e.dataTransfer.dropEffect = "move";
  5833. } else {
  5834. e.dataTransfer.dropEffect = "copy";
  5835. }
  5836. e.stopPropagation();
  5837. e.preventDefault();
  5838. });
  5839. disposeSupport.attach(element, "dragenter", function(e) {
  5840. if (!isOrSetDropDisabled()) {
  5841. if (!isValidFileDrag(e)) {
  5842. return;
  5843. }
  5844. options.onEnter(e);
  5845. }
  5846. });
  5847. disposeSupport.attach(element, "dragleave", function(e) {
  5848. if (!isValidFileDrag(e)) {
  5849. return;
  5850. }
  5851. options.onLeave(e);
  5852. var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
  5853. if (qq(this).contains(relatedTarget)) {
  5854. return;
  5855. }
  5856. options.onLeaveNotDescendants(e);
  5857. });
  5858. disposeSupport.attach(element, "drop", function(e) {
  5859. if (!isOrSetDropDisabled()) {
  5860. if (!isValidFileDrag(e)) {
  5861. return;
  5862. }
  5863. e.preventDefault();
  5864. e.stopPropagation();
  5865. options.onDrop(e);
  5866. triggerHidezonesEvent();
  5867. }
  5868. });
  5869. }
  5870. disableDropOutside();
  5871. attachEvents();
  5872. qq.extend(this, {
  5873. dropDisabled: function(isDisabled) {
  5874. return isOrSetDropDisabled(isDisabled);
  5875. },
  5876. dispose: function() {
  5877. disposeSupport.dispose();
  5878. },
  5879. getElement: function() {
  5880. return element;
  5881. }
  5882. });
  5883. this._testing = {};
  5884. this._testing.isValidFileDrag = isValidFileDrag;
  5885. };
  5886. (function() {
  5887. "use strict";
  5888. qq.uiPublicApi = {
  5889. addInitialFiles: function(cannedFileList) {
  5890. this._parent.prototype.addInitialFiles.apply(this, arguments);
  5891. this._templating.addCacheToDom();
  5892. },
  5893. clearStoredFiles: function() {
  5894. this._parent.prototype.clearStoredFiles.apply(this, arguments);
  5895. this._templating.clearFiles();
  5896. },
  5897. addExtraDropzone: function(element) {
  5898. this._dnd && this._dnd.setupExtraDropzone(element);
  5899. },
  5900. removeExtraDropzone: function(element) {
  5901. if (this._dnd) {
  5902. return this._dnd.removeDropzone(element);
  5903. }
  5904. },
  5905. getItemByFileId: function(id) {
  5906. if (!this._templating.isHiddenForever(id)) {
  5907. return this._templating.getFileContainer(id);
  5908. }
  5909. },
  5910. reset: function() {
  5911. this._parent.prototype.reset.apply(this, arguments);
  5912. this._templating.reset();
  5913. if (!this._options.button && this._templating.getButton()) {
  5914. this._defaultButtonId = this._createUploadButton({
  5915. element: this._templating.getButton(),
  5916. title: this._options.text.fileInputTitle
  5917. }).getButtonId();
  5918. }
  5919. if (this._dnd) {
  5920. this._dnd.dispose();
  5921. this._dnd = this._setupDragAndDrop();
  5922. }
  5923. this._totalFilesInBatch = 0;
  5924. this._filesInBatchAddedToUi = 0;
  5925. this._setupClickAndEditEventHandlers();
  5926. },
  5927. setName: function(id, newName) {
  5928. var formattedFilename = this._options.formatFileName(newName);
  5929. this._parent.prototype.setName.apply(this, arguments);
  5930. this._templating.updateFilename(id, formattedFilename);
  5931. },
  5932. pauseUpload: function(id) {
  5933. var paused = this._parent.prototype.pauseUpload.apply(this, arguments);
  5934. paused && this._templating.uploadPaused(id);
  5935. return paused;
  5936. },
  5937. continueUpload: function(id) {
  5938. var continued = this._parent.prototype.continueUpload.apply(this, arguments);
  5939. continued && this._templating.uploadContinued(id);
  5940. return continued;
  5941. },
  5942. getId: function(fileContainerOrChildEl) {
  5943. return this._templating.getFileId(fileContainerOrChildEl);
  5944. },
  5945. getDropTarget: function(fileId) {
  5946. var file = this.getFile(fileId);
  5947. return file.qqDropTarget;
  5948. }
  5949. };
  5950. qq.uiPrivateApi = {
  5951. _getButton: function(buttonId) {
  5952. var button = this._parent.prototype._getButton.apply(this, arguments);
  5953. if (!button) {
  5954. if (buttonId === this._defaultButtonId) {
  5955. button = this._templating.getButton();
  5956. }
  5957. }
  5958. return button;
  5959. },
  5960. _removeFileItem: function(fileId) {
  5961. this._templating.removeFile(fileId);
  5962. },
  5963. _setupClickAndEditEventHandlers: function() {
  5964. this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent();
  5965. this._focusinEventSupported = !qq.firefox();
  5966. if (this._isEditFilenameEnabled()) {
  5967. this._filenameClickHandler = this._bindFilenameClickEvent();
  5968. this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent();
  5969. this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent();
  5970. }
  5971. },
  5972. _setupDragAndDrop: function() {
  5973. var self = this, dropZoneElements = this._options.dragAndDrop.extraDropzones, templating = this._templating, defaultDropZone = templating.getDropZone();
  5974. defaultDropZone && dropZoneElements.push(defaultDropZone);
  5975. return new qq.DragAndDrop({
  5976. dropZoneElements: dropZoneElements,
  5977. allowMultipleItems: this._options.multiple,
  5978. classes: {
  5979. dropActive: this._options.classes.dropActive
  5980. },
  5981. callbacks: {
  5982. processingDroppedFiles: function() {
  5983. templating.showDropProcessing();
  5984. },
  5985. processingDroppedFilesComplete: function(files, targetEl) {
  5986. templating.hideDropProcessing();
  5987. qq.each(files, function(idx, file) {
  5988. file.qqDropTarget = targetEl;
  5989. });
  5990. if (files.length) {
  5991. self.addFiles(files, null, null);
  5992. }
  5993. },
  5994. dropError: function(code, errorData) {
  5995. self._itemError(code, errorData);
  5996. },
  5997. dropLog: function(message, level) {
  5998. self.log(message, level);
  5999. }
  6000. }
  6001. });
  6002. },
  6003. _bindFileButtonsClickEvent: function() {
  6004. var self = this;
  6005. return new qq.FileButtonsClickHandler({
  6006. templating: this._templating,
  6007. log: function(message, lvl) {
  6008. self.log(message, lvl);
  6009. },
  6010. onDeleteFile: function(fileId) {
  6011. self.deleteFile(fileId);
  6012. },
  6013. onCancel: function(fileId) {
  6014. self.cancel(fileId);
  6015. },
  6016. onRetry: function(fileId) {
  6017. self.retry(fileId);
  6018. },
  6019. onPause: function(fileId) {
  6020. self.pauseUpload(fileId);
  6021. },
  6022. onContinue: function(fileId) {
  6023. self.continueUpload(fileId);
  6024. },
  6025. onGetName: function(fileId) {
  6026. return self.getName(fileId);
  6027. }
  6028. });
  6029. },
  6030. _isEditFilenameEnabled: function() {
  6031. return this._templating.isEditFilenamePossible() && !this._options.autoUpload && qq.FilenameClickHandler && qq.FilenameInputFocusHandler && qq.FilenameInputFocusHandler;
  6032. },
  6033. _filenameEditHandler: function() {
  6034. var self = this, templating = this._templating;
  6035. return {
  6036. templating: templating,
  6037. log: function(message, lvl) {
  6038. self.log(message, lvl);
  6039. },
  6040. onGetUploadStatus: function(fileId) {
  6041. return self.getUploads({
  6042. id: fileId
  6043. }).status;
  6044. },
  6045. onGetName: function(fileId) {
  6046. return self.getName(fileId);
  6047. },
  6048. onSetName: function(id, newName) {
  6049. self.setName(id, newName);
  6050. },
  6051. onEditingStatusChange: function(id, isEditing) {
  6052. var qqInput = qq(templating.getEditInput(id)), qqFileContainer = qq(templating.getFileContainer(id));
  6053. if (isEditing) {
  6054. qqInput.addClass("qq-editing");
  6055. templating.hideFilename(id);
  6056. templating.hideEditIcon(id);
  6057. } else {
  6058. qqInput.removeClass("qq-editing");
  6059. templating.showFilename(id);
  6060. templating.showEditIcon(id);
  6061. }
  6062. qqFileContainer.addClass("qq-temp").removeClass("qq-temp");
  6063. }
  6064. };
  6065. },
  6066. _onUploadStatusChange: function(id, oldStatus, newStatus) {
  6067. this._parent.prototype._onUploadStatusChange.apply(this, arguments);
  6068. if (this._isEditFilenameEnabled()) {
  6069. if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) {
  6070. this._templating.markFilenameEditable(id);
  6071. this._templating.hideEditIcon(id);
  6072. }
  6073. }
  6074. if (oldStatus === qq.status.UPLOAD_RETRYING && newStatus === qq.status.UPLOADING) {
  6075. this._templating.hideRetry(id);
  6076. this._templating.setStatusText(id);
  6077. qq(this._templating.getFileContainer(id)).removeClass(this._classes.retrying);
  6078. } else if (newStatus === qq.status.UPLOAD_FAILED) {
  6079. this._templating.hidePause(id);
  6080. }
  6081. },
  6082. _bindFilenameInputFocusInEvent: function() {
  6083. var spec = qq.extend({}, this._filenameEditHandler());
  6084. return new qq.FilenameInputFocusInHandler(spec);
  6085. },
  6086. _bindFilenameInputFocusEvent: function() {
  6087. var spec = qq.extend({}, this._filenameEditHandler());
  6088. return new qq.FilenameInputFocusHandler(spec);
  6089. },
  6090. _bindFilenameClickEvent: function() {
  6091. var spec = qq.extend({}, this._filenameEditHandler());
  6092. return new qq.FilenameClickHandler(spec);
  6093. },
  6094. _storeForLater: function(id) {
  6095. this._parent.prototype._storeForLater.apply(this, arguments);
  6096. this._templating.hideSpinner(id);
  6097. },
  6098. _onAllComplete: function(successful, failed) {
  6099. this._parent.prototype._onAllComplete.apply(this, arguments);
  6100. this._templating.resetTotalProgress();
  6101. },
  6102. _onSubmit: function(id, name) {
  6103. var file = this.getFile(id);
  6104. if (file && file.qqPath && this._options.dragAndDrop.reportDirectoryPaths) {
  6105. this._paramsStore.addReadOnly(id, {
  6106. qqpath: file.qqPath
  6107. });
  6108. }
  6109. this._parent.prototype._onSubmit.apply(this, arguments);
  6110. this._addToList(id, name);
  6111. },
  6112. _onSubmitted: function(id) {
  6113. if (this._isEditFilenameEnabled()) {
  6114. this._templating.markFilenameEditable(id);
  6115. this._templating.showEditIcon(id);
  6116. if (!this._focusinEventSupported) {
  6117. this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id));
  6118. }
  6119. }
  6120. },
  6121. _onProgress: function(id, name, loaded, total) {
  6122. this._parent.prototype._onProgress.apply(this, arguments);
  6123. this._templating.updateProgress(id, loaded, total);
  6124. if (total === 0 || Math.round(loaded / total * 100) === 100) {
  6125. this._templating.hideCancel(id);
  6126. this._templating.hidePause(id);
  6127. this._templating.hideProgress(id);
  6128. this._templating.setStatusText(id, this._options.text.waitingForResponse);
  6129. this._displayFileSize(id);
  6130. } else {
  6131. this._displayFileSize(id, loaded, total);
  6132. }
  6133. },
  6134. _onTotalProgress: function(loaded, total) {
  6135. this._parent.prototype._onTotalProgress.apply(this, arguments);
  6136. this._templating.updateTotalProgress(loaded, total);
  6137. },
  6138. _onComplete: function(id, name, result, xhr) {
  6139. var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments), templating = this._templating, fileContainer = templating.getFileContainer(id), self = this;
  6140. function completeUpload(result) {
  6141. if (!fileContainer) {
  6142. return;
  6143. }
  6144. templating.setStatusText(id);
  6145. qq(fileContainer).removeClass(self._classes.retrying);
  6146. templating.hideProgress(id);
  6147. if (self.getUploads({
  6148. id: id
  6149. }).status !== qq.status.UPLOAD_FAILED) {
  6150. templating.hideCancel(id);
  6151. }
  6152. templating.hideSpinner(id);
  6153. if (result.success) {
  6154. self._markFileAsSuccessful(id);
  6155. } else {
  6156. qq(fileContainer).addClass(self._classes.fail);
  6157. templating.showCancel(id);
  6158. if (templating.isRetryPossible() && !self._preventRetries[id]) {
  6159. qq(fileContainer).addClass(self._classes.retryable);
  6160. templating.showRetry(id);
  6161. }
  6162. self._controlFailureTextDisplay(id, result);
  6163. }
  6164. }
  6165. if (parentRetVal instanceof qq.Promise) {
  6166. parentRetVal.done(function(newResult) {
  6167. completeUpload(newResult);
  6168. });
  6169. } else {
  6170. completeUpload(result);
  6171. }
  6172. return parentRetVal;
  6173. },
  6174. _markFileAsSuccessful: function(id) {
  6175. var templating = this._templating;
  6176. if (this._isDeletePossible()) {
  6177. templating.showDeleteButton(id);
  6178. }
  6179. qq(templating.getFileContainer(id)).addClass(this._classes.success);
  6180. this._maybeUpdateThumbnail(id);
  6181. },
  6182. _onUploadPrep: function(id) {
  6183. this._parent.prototype._onUploadPrep.apply(this, arguments);
  6184. this._templating.showSpinner(id);
  6185. },
  6186. _onUpload: function(id, name) {
  6187. var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments);
  6188. this._templating.showSpinner(id);
  6189. return parentRetVal;
  6190. },
  6191. _onUploadChunk: function(id, chunkData) {
  6192. this._parent.prototype._onUploadChunk.apply(this, arguments);
  6193. if (chunkData.partIndex > 0 && this._handler.isResumable(id)) {
  6194. this._templating.allowPause(id);
  6195. }
  6196. },
  6197. _onCancel: function(id, name) {
  6198. this._parent.prototype._onCancel.apply(this, arguments);
  6199. this._removeFileItem(id);
  6200. if (this._getNotFinished() === 0) {
  6201. this._templating.resetTotalProgress();
  6202. }
  6203. },
  6204. _onBeforeAutoRetry: function(id) {
  6205. var retryNumForDisplay, maxAuto, retryNote;
  6206. this._parent.prototype._onBeforeAutoRetry.apply(this, arguments);
  6207. this._showCancelLink(id);
  6208. if (this._options.retry.showAutoRetryNote) {
  6209. retryNumForDisplay = this._autoRetries[id];
  6210. maxAuto = this._options.retry.maxAutoAttempts;
  6211. retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay);
  6212. retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto);
  6213. this._templating.setStatusText(id, retryNote);
  6214. qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying);
  6215. }
  6216. },
  6217. _onBeforeManualRetry: function(id) {
  6218. if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) {
  6219. this._templating.resetProgress(id);
  6220. qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail);
  6221. this._templating.setStatusText(id);
  6222. this._templating.showSpinner(id);
  6223. this._showCancelLink(id);
  6224. return true;
  6225. } else {
  6226. qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable);
  6227. this._templating.showRetry(id);
  6228. return false;
  6229. }
  6230. },
  6231. _onSubmitDelete: function(id) {
  6232. var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this);
  6233. this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback);
  6234. },
  6235. _onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) {
  6236. if (this._options.deleteFile.forceConfirm) {
  6237. this._showDeleteConfirm.apply(this, arguments);
  6238. } else {
  6239. this._sendDeleteRequest.apply(this, arguments);
  6240. }
  6241. },
  6242. _onDeleteComplete: function(id, xhr, isError) {
  6243. this._parent.prototype._onDeleteComplete.apply(this, arguments);
  6244. this._templating.hideSpinner(id);
  6245. if (isError) {
  6246. this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText);
  6247. this._templating.showDeleteButton(id);
  6248. } else {
  6249. this._removeFileItem(id);
  6250. }
  6251. },
  6252. _sendDeleteRequest: function(id, uuid, additionalMandatedParams) {
  6253. this._templating.hideDeleteButton(id);
  6254. this._templating.showSpinner(id);
  6255. this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText);
  6256. this._deleteHandler.sendDelete.apply(this, arguments);
  6257. },
  6258. _showDeleteConfirm: function(id, uuid, mandatedParams) {
  6259. var fileName = this.getName(id), confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName), uuid = this.getUuid(id), deleteRequestArgs = arguments, self = this, retVal;
  6260. retVal = this._options.showConfirm(confirmMessage);
  6261. if (qq.isGenericPromise(retVal)) {
  6262. retVal.then(function() {
  6263. self._sendDeleteRequest.apply(self, deleteRequestArgs);
  6264. });
  6265. } else if (retVal !== false) {
  6266. self._sendDeleteRequest.apply(self, deleteRequestArgs);
  6267. }
  6268. },
  6269. _addToList: function(id, name, canned) {
  6270. var prependData, prependIndex = 0, dontDisplay = this._handler.isProxied(id) && this._options.scaling.hideScaled, record;
  6271. if (this._options.display.prependFiles) {
  6272. if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) {
  6273. prependIndex = this._filesInBatchAddedToUi - 1;
  6274. }
  6275. prependData = {
  6276. index: prependIndex
  6277. };
  6278. }
  6279. if (!canned) {
  6280. if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) {
  6281. this._templating.disableCancel();
  6282. }
  6283. if (!this._options.multiple) {
  6284. record = this.getUploads({
  6285. id: id
  6286. });
  6287. this._handledProxyGroup = this._handledProxyGroup || record.proxyGroupId;
  6288. if (record.proxyGroupId !== this._handledProxyGroup || !record.proxyGroupId) {
  6289. this._handler.cancelAll();
  6290. this._clearList();
  6291. this._handledProxyGroup = null;
  6292. }
  6293. }
  6294. }
  6295. if (canned) {
  6296. this._templating.addFileToCache(id, this._options.formatFileName(name), prependData, dontDisplay);
  6297. this._templating.updateThumbnail(id, this._thumbnailUrls[id], true, this._options.thumbnails.customResizer);
  6298. } else {
  6299. this._templating.addFile(id, this._options.formatFileName(name), prependData, dontDisplay);
  6300. this._templating.generatePreview(id, this.getFile(id), this._options.thumbnails.customResizer);
  6301. }
  6302. this._filesInBatchAddedToUi += 1;
  6303. if (canned || this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading) {
  6304. this._displayFileSize(id);
  6305. }
  6306. },
  6307. _clearList: function() {
  6308. this._templating.clearFiles();
  6309. this.clearStoredFiles();
  6310. },
  6311. _displayFileSize: function(id, loadedSize, totalSize) {
  6312. var size = this.getSize(id), sizeForDisplay = this._formatSize(size);
  6313. if (size >= 0) {
  6314. if (loadedSize !== undefined && totalSize !== undefined) {
  6315. sizeForDisplay = this._formatProgress(loadedSize, totalSize);
  6316. }
  6317. this._templating.updateSize(id, sizeForDisplay);
  6318. }
  6319. },
  6320. _formatProgress: function(uploadedSize, totalSize) {
  6321. var message = this._options.text.formatProgress;
  6322. function r(name, replacement) {
  6323. message = message.replace(name, replacement);
  6324. }
  6325. r("{percent}", Math.round(uploadedSize / totalSize * 100));
  6326. r("{total_size}", this._formatSize(totalSize));
  6327. return message;
  6328. },
  6329. _controlFailureTextDisplay: function(id, response) {
  6330. var mode, responseProperty, failureReason;
  6331. mode = this._options.failedUploadTextDisplay.mode;
  6332. responseProperty = this._options.failedUploadTextDisplay.responseProperty;
  6333. if (mode === "custom") {
  6334. failureReason = response[responseProperty];
  6335. if (!failureReason) {
  6336. failureReason = this._options.text.failUpload;
  6337. }
  6338. this._templating.setStatusText(id, failureReason);
  6339. if (this._options.failedUploadTextDisplay.enableTooltip) {
  6340. this._showTooltip(id, failureReason);
  6341. }
  6342. } else if (mode === "default") {
  6343. this._templating.setStatusText(id, this._options.text.failUpload);
  6344. } else if (mode !== "none") {
  6345. this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn");
  6346. }
  6347. },
  6348. _showTooltip: function(id, text) {
  6349. this._templating.getFileContainer(id).title = text;
  6350. },
  6351. _showCancelLink: function(id) {
  6352. if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {
  6353. this._templating.showCancel(id);
  6354. }
  6355. },
  6356. _itemError: function(code, name, item) {
  6357. var message = this._parent.prototype._itemError.apply(this, arguments);
  6358. this._options.showMessage(message);
  6359. },
  6360. _batchError: function(message) {
  6361. this._parent.prototype._batchError.apply(this, arguments);
  6362. this._options.showMessage(message);
  6363. },
  6364. _setupPastePrompt: function() {
  6365. var self = this;
  6366. this._options.callbacks.onPasteReceived = function() {
  6367. var message = self._options.paste.namePromptMessage, defaultVal = self._options.paste.defaultName;
  6368. return self._options.showPrompt(message, defaultVal);
  6369. };
  6370. },
  6371. _fileOrBlobRejected: function(id, name) {
  6372. this._totalFilesInBatch -= 1;
  6373. this._parent.prototype._fileOrBlobRejected.apply(this, arguments);
  6374. },
  6375. _prepareItemsForUpload: function(items, params, endpoint) {
  6376. this._totalFilesInBatch = items.length;
  6377. this._filesInBatchAddedToUi = 0;
  6378. this._parent.prototype._prepareItemsForUpload.apply(this, arguments);
  6379. },
  6380. _maybeUpdateThumbnail: function(fileId) {
  6381. var thumbnailUrl = this._thumbnailUrls[fileId], fileStatus = this.getUploads({
  6382. id: fileId
  6383. }).status;
  6384. if (fileStatus !== qq.status.DELETED && (thumbnailUrl || this._options.thumbnails.placeholders.waitUntilResponse || !qq.supportedFeatures.imagePreviews)) {
  6385. this._templating.updateThumbnail(fileId, thumbnailUrl, this._options.thumbnails.customResizer);
  6386. }
  6387. },
  6388. _addCannedFile: function(sessionData) {
  6389. var id = this._parent.prototype._addCannedFile.apply(this, arguments);
  6390. this._addToList(id, this.getName(id), true);
  6391. this._templating.hideSpinner(id);
  6392. this._templating.hideCancel(id);
  6393. this._markFileAsSuccessful(id);
  6394. return id;
  6395. },
  6396. _setSize: function(id, newSize) {
  6397. this._parent.prototype._setSize.apply(this, arguments);
  6398. this._templating.updateSize(id, this._formatSize(newSize));
  6399. },
  6400. _sessionRequestComplete: function() {
  6401. this._templating.addCacheToDom();
  6402. this._parent.prototype._sessionRequestComplete.apply(this, arguments);
  6403. }
  6404. };
  6405. })();
  6406. qq.FineUploader = function(o, namespace) {
  6407. "use strict";
  6408. var self = this;
  6409. this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic;
  6410. this._parent.apply(this, arguments);
  6411. qq.extend(this._options, {
  6412. element: null,
  6413. button: null,
  6414. listElement: null,
  6415. dragAndDrop: {
  6416. extraDropzones: [],
  6417. reportDirectoryPaths: false
  6418. },
  6419. text: {
  6420. formatProgress: "{percent}% of {total_size}",
  6421. failUpload: "Upload failed",
  6422. waitingForResponse: "Processing...",
  6423. paused: "Paused"
  6424. },
  6425. template: "qq-template",
  6426. classes: {
  6427. retrying: "qq-upload-retrying",
  6428. retryable: "qq-upload-retryable",
  6429. success: "qq-upload-success",
  6430. fail: "qq-upload-fail",
  6431. editable: "qq-editable",
  6432. hide: "qq-hide",
  6433. dropActive: "qq-upload-drop-area-active"
  6434. },
  6435. failedUploadTextDisplay: {
  6436. mode: "default",
  6437. responseProperty: "error",
  6438. enableTooltip: true
  6439. },
  6440. messages: {
  6441. tooManyFilesError: "You may only drop one file",
  6442. unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind."
  6443. },
  6444. retry: {
  6445. showAutoRetryNote: true,
  6446. autoRetryNote: "Retrying {retryNum}/{maxAuto}..."
  6447. },
  6448. deleteFile: {
  6449. forceConfirm: false,
  6450. confirmMessage: "Are you sure you want to delete {filename}?",
  6451. deletingStatusText: "Deleting...",
  6452. deletingFailedText: "Delete failed"
  6453. },
  6454. display: {
  6455. fileSizeOnSubmit: false,
  6456. prependFiles: false
  6457. },
  6458. paste: {
  6459. promptForName: false,
  6460. namePromptMessage: "Please name this image"
  6461. },
  6462. thumbnails: {
  6463. customResizer: null,
  6464. maxCount: 0,
  6465. placeholders: {
  6466. waitUntilResponse: false,
  6467. notAvailablePath: null,
  6468. waitingPath: null
  6469. },
  6470. timeBetweenThumbs: 750
  6471. },
  6472. scaling: {
  6473. hideScaled: false
  6474. },
  6475. showMessage: function(message) {
  6476. if (self._templating.hasDialog("alert")) {
  6477. return self._templating.showDialog("alert", message);
  6478. } else {
  6479. setTimeout(function() {
  6480. window.alert(message);
  6481. }, 0);
  6482. }
  6483. },
  6484. showConfirm: function(message) {
  6485. if (self._templating.hasDialog("confirm")) {
  6486. return self._templating.showDialog("confirm", message);
  6487. } else {
  6488. return window.confirm(message);
  6489. }
  6490. },
  6491. showPrompt: function(message, defaultValue) {
  6492. if (self._templating.hasDialog("prompt")) {
  6493. return self._templating.showDialog("prompt", message, defaultValue);
  6494. } else {
  6495. return window.prompt(message, defaultValue);
  6496. }
  6497. }
  6498. }, true);
  6499. qq.extend(this._options, o, true);
  6500. this._templating = new qq.Templating({
  6501. log: qq.bind(this.log, this),
  6502. templateIdOrEl: this._options.template,
  6503. containerEl: this._options.element,
  6504. fileContainerEl: this._options.listElement,
  6505. button: this._options.button,
  6506. imageGenerator: this._imageGenerator,
  6507. classes: {
  6508. hide: this._options.classes.hide,
  6509. editable: this._options.classes.editable
  6510. },
  6511. limits: {
  6512. maxThumbs: this._options.thumbnails.maxCount,
  6513. timeBetweenThumbs: this._options.thumbnails.timeBetweenThumbs
  6514. },
  6515. placeholders: {
  6516. waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse,
  6517. thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath,
  6518. waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath
  6519. },
  6520. text: this._options.text
  6521. });
  6522. if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
  6523. this._templating.renderFailure(this._options.messages.unsupportedBrowserIos8Safari);
  6524. } else if (!qq.supportedFeatures.uploading || this._options.cors.expected && !qq.supportedFeatures.uploadCors) {
  6525. this._templating.renderFailure(this._options.messages.unsupportedBrowser);
  6526. } else {
  6527. this._wrapCallbacks();
  6528. this._templating.render();
  6529. this._classes = this._options.classes;
  6530. if (!this._options.button && this._templating.getButton()) {
  6531. this._defaultButtonId = this._createUploadButton({
  6532. element: this._templating.getButton(),
  6533. title: this._options.text.fileInputTitle
  6534. }).getButtonId();
  6535. }
  6536. this._setupClickAndEditEventHandlers();
  6537. if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) {
  6538. this._dnd = this._setupDragAndDrop();
  6539. }
  6540. if (this._options.paste.targetElement && this._options.paste.promptForName) {
  6541. if (qq.PasteSupport) {
  6542. this._setupPastePrompt();
  6543. } else {
  6544. this.log("Paste support module not found.", "error");
  6545. }
  6546. }
  6547. this._totalFilesInBatch = 0;
  6548. this._filesInBatchAddedToUi = 0;
  6549. }
  6550. };
  6551. qq.extend(qq.FineUploader.prototype, qq.basePublicApi);
  6552. qq.extend(qq.FineUploader.prototype, qq.basePrivateApi);
  6553. qq.extend(qq.FineUploader.prototype, qq.uiPublicApi);
  6554. qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi);
  6555. qq.Templating = function(spec) {
  6556. "use strict";
  6557. var FILE_ID_ATTR = "qq-file-id", FILE_CLASS_PREFIX = "qq-file-id-", THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size", THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale", HIDE_DROPZONE_ATTR = "qq-hide-dropzone", DROPZPONE_TEXT_ATTR = "qq-drop-area-text", IN_PROGRESS_CLASS = "qq-in-progress", HIDDEN_FOREVER_CLASS = "qq-hidden-forever", fileBatch = {
  6558. content: document.createDocumentFragment(),
  6559. map: {}
  6560. }, isCancelDisabled = false, generatedThumbnails = 0, thumbnailQueueMonitorRunning = false, thumbGenerationQueue = [], thumbnailMaxSize = -1, options = {
  6561. log: null,
  6562. limits: {
  6563. maxThumbs: 0,
  6564. timeBetweenThumbs: 750
  6565. },
  6566. templateIdOrEl: "qq-template",
  6567. containerEl: null,
  6568. fileContainerEl: null,
  6569. button: null,
  6570. imageGenerator: null,
  6571. classes: {
  6572. hide: "qq-hide",
  6573. editable: "qq-editable"
  6574. },
  6575. placeholders: {
  6576. waitUntilUpdate: false,
  6577. thumbnailNotAvailable: null,
  6578. waitingForThumbnail: null
  6579. },
  6580. text: {
  6581. paused: "Paused"
  6582. }
  6583. }, selectorClasses = {
  6584. button: "qq-upload-button-selector",
  6585. alertDialog: "qq-alert-dialog-selector",
  6586. dialogCancelButton: "qq-cancel-button-selector",
  6587. confirmDialog: "qq-confirm-dialog-selector",
  6588. dialogMessage: "qq-dialog-message-selector",
  6589. dialogOkButton: "qq-ok-button-selector",
  6590. promptDialog: "qq-prompt-dialog-selector",
  6591. uploader: "qq-uploader-selector",
  6592. drop: "qq-upload-drop-area-selector",
  6593. list: "qq-upload-list-selector",
  6594. progressBarContainer: "qq-progress-bar-container-selector",
  6595. progressBar: "qq-progress-bar-selector",
  6596. totalProgressBarContainer: "qq-total-progress-bar-container-selector",
  6597. totalProgressBar: "qq-total-progress-bar-selector",
  6598. file: "qq-upload-file-selector",
  6599. spinner: "qq-upload-spinner-selector",
  6600. size: "qq-upload-size-selector",
  6601. cancel: "qq-upload-cancel-selector",
  6602. pause: "qq-upload-pause-selector",
  6603. continueButton: "qq-upload-continue-selector",
  6604. deleteButton: "qq-upload-delete-selector",
  6605. retry: "qq-upload-retry-selector",
  6606. statusText: "qq-upload-status-text-selector",
  6607. editFilenameInput: "qq-edit-filename-selector",
  6608. editNameIcon: "qq-edit-filename-icon-selector",
  6609. dropText: "qq-upload-drop-area-text-selector",
  6610. dropProcessing: "qq-drop-processing-selector",
  6611. dropProcessingSpinner: "qq-drop-processing-spinner-selector",
  6612. thumbnail: "qq-thumbnail-selector"
  6613. }, previewGeneration = {}, cachedThumbnailNotAvailableImg = new qq.Promise(), cachedWaitingForThumbnailImg = new qq.Promise(), log, isEditElementsExist, isRetryElementExist, templateDom, container, fileList, showThumbnails, serverScale, cacheThumbnailPlaceholders = function() {
  6614. var notAvailableUrl = options.placeholders.thumbnailNotAvailable, waitingUrl = options.placeholders.waitingForThumbnail, spec = {
  6615. maxSize: thumbnailMaxSize,
  6616. scale: serverScale
  6617. };
  6618. if (showThumbnails) {
  6619. if (notAvailableUrl) {
  6620. options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then(function(updatedImg) {
  6621. cachedThumbnailNotAvailableImg.success(updatedImg);
  6622. }, function() {
  6623. cachedThumbnailNotAvailableImg.failure();
  6624. log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error");
  6625. });
  6626. } else {
  6627. cachedThumbnailNotAvailableImg.failure();
  6628. }
  6629. if (waitingUrl) {
  6630. options.imageGenerator.generate(waitingUrl, new Image(), spec).then(function(updatedImg) {
  6631. cachedWaitingForThumbnailImg.success(updatedImg);
  6632. }, function() {
  6633. cachedWaitingForThumbnailImg.failure();
  6634. log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error");
  6635. });
  6636. } else {
  6637. cachedWaitingForThumbnailImg.failure();
  6638. }
  6639. }
  6640. }, displayWaitingImg = function(thumbnail) {
  6641. var waitingImgPlacement = new qq.Promise();
  6642. cachedWaitingForThumbnailImg.then(function(img) {
  6643. maybeScalePlaceholderViaCss(img, thumbnail);
  6644. if (!thumbnail.src) {
  6645. thumbnail.src = img.src;
  6646. thumbnail.onload = function() {
  6647. thumbnail.onload = null;
  6648. show(thumbnail);
  6649. waitingImgPlacement.success();
  6650. };
  6651. } else {
  6652. waitingImgPlacement.success();
  6653. }
  6654. }, function() {
  6655. hide(thumbnail);
  6656. waitingImgPlacement.success();
  6657. });
  6658. return waitingImgPlacement;
  6659. }, generateNewPreview = function(id, blob, spec) {
  6660. var thumbnail = getThumbnail(id);
  6661. log("Generating new thumbnail for " + id);
  6662. blob.qqThumbnailId = id;
  6663. return options.imageGenerator.generate(blob, thumbnail, spec).then(function() {
  6664. generatedThumbnails++;
  6665. show(thumbnail);
  6666. previewGeneration[id].success();
  6667. }, function() {
  6668. previewGeneration[id].failure();
  6669. if (!options.placeholders.waitUntilUpdate) {
  6670. maybeSetDisplayNotAvailableImg(id, thumbnail);
  6671. }
  6672. });
  6673. }, generateNextQueuedPreview = function() {
  6674. if (thumbGenerationQueue.length) {
  6675. thumbnailQueueMonitorRunning = true;
  6676. var queuedThumbRequest = thumbGenerationQueue.shift();
  6677. if (queuedThumbRequest.update) {
  6678. processUpdateQueuedPreviewRequest(queuedThumbRequest);
  6679. } else {
  6680. processNewQueuedPreviewRequest(queuedThumbRequest);
  6681. }
  6682. } else {
  6683. thumbnailQueueMonitorRunning = false;
  6684. }
  6685. }, getCancel = function(id) {
  6686. return getTemplateEl(getFile(id), selectorClasses.cancel);
  6687. }, getContinue = function(id) {
  6688. return getTemplateEl(getFile(id), selectorClasses.continueButton);
  6689. }, getDialog = function(type) {
  6690. return getTemplateEl(container, selectorClasses[type + "Dialog"]);
  6691. }, getDelete = function(id) {
  6692. return getTemplateEl(getFile(id), selectorClasses.deleteButton);
  6693. }, getDropProcessing = function() {
  6694. return getTemplateEl(container, selectorClasses.dropProcessing);
  6695. }, getEditIcon = function(id) {
  6696. return getTemplateEl(getFile(id), selectorClasses.editNameIcon);
  6697. }, getFile = function(id) {
  6698. return fileBatch.map[id] || qq(fileList).getFirstByClass(FILE_CLASS_PREFIX + id);
  6699. }, getFilename = function(id) {
  6700. return getTemplateEl(getFile(id), selectorClasses.file);
  6701. }, getPause = function(id) {
  6702. return getTemplateEl(getFile(id), selectorClasses.pause);
  6703. }, getProgress = function(id) {
  6704. if (id == null) {
  6705. return getTemplateEl(container, selectorClasses.totalProgressBarContainer) || getTemplateEl(container, selectorClasses.totalProgressBar);
  6706. }
  6707. return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) || getTemplateEl(getFile(id), selectorClasses.progressBar);
  6708. }, getRetry = function(id) {
  6709. return getTemplateEl(getFile(id), selectorClasses.retry);
  6710. }, getSize = function(id) {
  6711. return getTemplateEl(getFile(id), selectorClasses.size);
  6712. }, getSpinner = function(id) {
  6713. return getTemplateEl(getFile(id), selectorClasses.spinner);
  6714. }, getTemplateEl = function(context, cssClass) {
  6715. return context && qq(context).getFirstByClass(cssClass);
  6716. }, getThumbnail = function(id) {
  6717. return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail);
  6718. }, hide = function(el) {
  6719. el && qq(el).addClass(options.classes.hide);
  6720. }, maybeScalePlaceholderViaCss = function(placeholder, thumbnail) {
  6721. var maxWidth = placeholder.style.maxWidth, maxHeight = placeholder.style.maxHeight;
  6722. if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) {
  6723. qq(thumbnail).css({
  6724. maxWidth: maxWidth,
  6725. maxHeight: maxHeight
  6726. });
  6727. }
  6728. }, maybeSetDisplayNotAvailableImg = function(id, thumbnail) {
  6729. var previewing = previewGeneration[id] || new qq.Promise().failure(), notAvailableImgPlacement = new qq.Promise();
  6730. cachedThumbnailNotAvailableImg.then(function(img) {
  6731. previewing.then(function() {
  6732. notAvailableImgPlacement.success();
  6733. }, function() {
  6734. maybeScalePlaceholderViaCss(img, thumbnail);
  6735. thumbnail.onload = function() {
  6736. thumbnail.onload = null;
  6737. notAvailableImgPlacement.success();
  6738. };
  6739. thumbnail.src = img.src;
  6740. show(thumbnail);
  6741. });
  6742. });
  6743. return notAvailableImgPlacement;
  6744. }, parseAndGetTemplate = function() {
  6745. var scriptEl, scriptHtml, fileListNode, tempTemplateEl, fileListEl, defaultButton, dropArea, thumbnail, dropProcessing, dropTextEl, uploaderEl;
  6746. log("Parsing template");
  6747. if (options.templateIdOrEl == null) {
  6748. throw new Error("You MUST specify either a template element or ID!");
  6749. }
  6750. if (qq.isString(options.templateIdOrEl)) {
  6751. scriptEl = document.getElementById(options.templateIdOrEl);
  6752. if (scriptEl === null) {
  6753. throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl));
  6754. }
  6755. scriptHtml = scriptEl.innerHTML;
  6756. } else {
  6757. if (options.templateIdOrEl.innerHTML === undefined) {
  6758. throw new Error("You have specified an invalid value for the template option! " + "It must be an ID or an Element.");
  6759. }
  6760. scriptHtml = options.templateIdOrEl.innerHTML;
  6761. }
  6762. scriptHtml = qq.trimStr(scriptHtml);
  6763. tempTemplateEl = document.createElement("div");
  6764. tempTemplateEl.appendChild(qq.toElement(scriptHtml));
  6765. uploaderEl = qq(tempTemplateEl).getFirstByClass(selectorClasses.uploader);
  6766. if (options.button) {
  6767. defaultButton = qq(tempTemplateEl).getFirstByClass(selectorClasses.button);
  6768. if (defaultButton) {
  6769. qq(defaultButton).remove();
  6770. }
  6771. }
  6772. if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) {
  6773. dropProcessing = qq(tempTemplateEl).getFirstByClass(selectorClasses.dropProcessing);
  6774. if (dropProcessing) {
  6775. qq(dropProcessing).remove();
  6776. }
  6777. }
  6778. dropArea = qq(tempTemplateEl).getFirstByClass(selectorClasses.drop);
  6779. if (dropArea && !qq.DragAndDrop) {
  6780. log("DnD module unavailable.", "info");
  6781. qq(dropArea).remove();
  6782. }
  6783. if (!qq.supportedFeatures.fileDrop) {
  6784. uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);
  6785. if (dropArea && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) {
  6786. qq(dropArea).css({
  6787. display: "none"
  6788. });
  6789. }
  6790. } else if (qq(uploaderEl).hasAttribute(DROPZPONE_TEXT_ATTR) && dropArea) {
  6791. dropTextEl = qq(dropArea).getFirstByClass(selectorClasses.dropText);
  6792. dropTextEl && qq(dropTextEl).remove();
  6793. }
  6794. thumbnail = qq(tempTemplateEl).getFirstByClass(selectorClasses.thumbnail);
  6795. if (!showThumbnails) {
  6796. thumbnail && qq(thumbnail).remove();
  6797. } else if (thumbnail) {
  6798. thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR));
  6799. thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null;
  6800. serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR);
  6801. }
  6802. showThumbnails = showThumbnails && thumbnail;
  6803. isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0;
  6804. isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0;
  6805. fileListNode = qq(tempTemplateEl).getFirstByClass(selectorClasses.list);
  6806. if (fileListNode == null) {
  6807. throw new Error("Could not find the file list container in the template!");
  6808. }
  6809. fileListEl = fileListNode.children[0].cloneNode(true);
  6810. fileListNode.innerHTML = "";
  6811. if (tempTemplateEl.getElementsByTagName("DIALOG").length) {
  6812. document.createElement("dialog");
  6813. }
  6814. log("Template parsing complete");
  6815. return {
  6816. template: tempTemplateEl,
  6817. fileTemplate: fileListEl
  6818. };
  6819. }, prependFile = function(el, index, fileList) {
  6820. var parentEl = fileList, beforeEl = parentEl.firstChild;
  6821. if (index > 0) {
  6822. beforeEl = qq(parentEl).children()[index].nextSibling;
  6823. }
  6824. parentEl.insertBefore(el, beforeEl);
  6825. }, processNewQueuedPreviewRequest = function(queuedThumbRequest) {
  6826. var id = queuedThumbRequest.id, optFileOrBlob = queuedThumbRequest.optFileOrBlob, relatedThumbnailId = optFileOrBlob && optFileOrBlob.qqThumbnailId, thumbnail = getThumbnail(id), spec = {
  6827. customResizeFunction: queuedThumbRequest.customResizeFunction,
  6828. maxSize: thumbnailMaxSize,
  6829. orient: true,
  6830. scale: true
  6831. };
  6832. if (qq.supportedFeatures.imagePreviews) {
  6833. if (thumbnail) {
  6834. if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
  6835. maybeSetDisplayNotAvailableImg(id, thumbnail);
  6836. generateNextQueuedPreview();
  6837. } else {
  6838. displayWaitingImg(thumbnail).done(function() {
  6839. previewGeneration[id] = new qq.Promise();
  6840. previewGeneration[id].done(function() {
  6841. setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
  6842. });
  6843. if (relatedThumbnailId != null) {
  6844. useCachedPreview(id, relatedThumbnailId);
  6845. } else {
  6846. generateNewPreview(id, optFileOrBlob, spec);
  6847. }
  6848. });
  6849. }
  6850. } else {
  6851. generateNextQueuedPreview();
  6852. }
  6853. } else if (thumbnail) {
  6854. displayWaitingImg(thumbnail);
  6855. generateNextQueuedPreview();
  6856. }
  6857. }, processUpdateQueuedPreviewRequest = function(queuedThumbRequest) {
  6858. var id = queuedThumbRequest.id, thumbnailUrl = queuedThumbRequest.thumbnailUrl, showWaitingImg = queuedThumbRequest.showWaitingImg, thumbnail = getThumbnail(id), spec = {
  6859. customResizeFunction: queuedThumbRequest.customResizeFunction,
  6860. scale: serverScale,
  6861. maxSize: thumbnailMaxSize
  6862. };
  6863. if (thumbnail) {
  6864. if (thumbnailUrl) {
  6865. if (options.limits.maxThumbs && options.limits.maxThumbs <= generatedThumbnails) {
  6866. maybeSetDisplayNotAvailableImg(id, thumbnail);
  6867. generateNextQueuedPreview();
  6868. } else {
  6869. if (showWaitingImg) {
  6870. displayWaitingImg(thumbnail);
  6871. }
  6872. return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then(function() {
  6873. show(thumbnail);
  6874. generatedThumbnails++;
  6875. setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
  6876. }, function() {
  6877. maybeSetDisplayNotAvailableImg(id, thumbnail);
  6878. setTimeout(generateNextQueuedPreview, options.limits.timeBetweenThumbs);
  6879. });
  6880. }
  6881. } else {
  6882. maybeSetDisplayNotAvailableImg(id, thumbnail);
  6883. generateNextQueuedPreview();
  6884. }
  6885. }
  6886. }, setProgressBarWidth = function(id, percent) {
  6887. var bar = getProgress(id), progressBarSelector = id == null ? selectorClasses.totalProgressBar : selectorClasses.progressBar;
  6888. if (bar && !qq(bar).hasClass(progressBarSelector)) {
  6889. bar = qq(bar).getFirstByClass(progressBarSelector);
  6890. }
  6891. if (bar) {
  6892. qq(bar).css({
  6893. width: percent + "%"
  6894. });
  6895. bar.setAttribute("aria-valuenow", percent);
  6896. }
  6897. }, show = function(el) {
  6898. el && qq(el).removeClass(options.classes.hide);
  6899. }, useCachedPreview = function(targetThumbnailId, cachedThumbnailId) {
  6900. var targetThumbnail = getThumbnail(targetThumbnailId), cachedThumbnail = getThumbnail(cachedThumbnailId);
  6901. log(qq.format("ID {} is the same file as ID {}. Will use generated thumbnail from ID {} instead.", targetThumbnailId, cachedThumbnailId, cachedThumbnailId));
  6902. previewGeneration[cachedThumbnailId].then(function() {
  6903. generatedThumbnails++;
  6904. previewGeneration[targetThumbnailId].success();
  6905. log(qq.format("Now using previously generated thumbnail created for ID {} on ID {}.", cachedThumbnailId, targetThumbnailId));
  6906. targetThumbnail.src = cachedThumbnail.src;
  6907. show(targetThumbnail);
  6908. }, function() {
  6909. previewGeneration[targetThumbnailId].failure();
  6910. if (!options.placeholders.waitUntilUpdate) {
  6911. maybeSetDisplayNotAvailableImg(targetThumbnailId, targetThumbnail);
  6912. }
  6913. });
  6914. };
  6915. qq.extend(options, spec);
  6916. log = options.log;
  6917. if (!qq.supportedFeatures.imagePreviews) {
  6918. options.limits.timeBetweenThumbs = 0;
  6919. options.limits.maxThumbs = 0;
  6920. }
  6921. container = options.containerEl;
  6922. showThumbnails = options.imageGenerator !== undefined;
  6923. templateDom = parseAndGetTemplate();
  6924. cacheThumbnailPlaceholders();
  6925. qq.extend(this, {
  6926. render: function() {
  6927. log("Rendering template in DOM.");
  6928. generatedThumbnails = 0;
  6929. container.appendChild(templateDom.template.cloneNode(true));
  6930. hide(getDropProcessing());
  6931. this.hideTotalProgress();
  6932. fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list);
  6933. log("Template rendering complete");
  6934. },
  6935. renderFailure: function(message) {
  6936. var cantRenderEl = qq.toElement(message);
  6937. container.innerHTML = "";
  6938. container.appendChild(cantRenderEl);
  6939. },
  6940. reset: function() {
  6941. this.render();
  6942. },
  6943. clearFiles: function() {
  6944. fileList.innerHTML = "";
  6945. },
  6946. disableCancel: function() {
  6947. isCancelDisabled = true;
  6948. },
  6949. addFile: function(id, name, prependInfo, hideForever, batch) {
  6950. var fileEl = templateDom.fileTemplate.cloneNode(true), fileNameEl = getTemplateEl(fileEl, selectorClasses.file), uploaderEl = getTemplateEl(container, selectorClasses.uploader), fileContainer = batch ? fileBatch.content : fileList, thumb;
  6951. if (batch) {
  6952. fileBatch.map[id] = fileEl;
  6953. }
  6954. qq(fileEl).addClass(FILE_CLASS_PREFIX + id);
  6955. uploaderEl.removeAttribute(DROPZPONE_TEXT_ATTR);
  6956. if (fileNameEl) {
  6957. qq(fileNameEl).setText(name);
  6958. fileNameEl.setAttribute("title", name);
  6959. }
  6960. fileEl.setAttribute(FILE_ID_ATTR, id);
  6961. if (prependInfo) {
  6962. prependFile(fileEl, prependInfo.index, fileContainer);
  6963. } else {
  6964. fileContainer.appendChild(fileEl);
  6965. }
  6966. if (hideForever) {
  6967. fileEl.style.display = "none";
  6968. qq(fileEl).addClass(HIDDEN_FOREVER_CLASS);
  6969. } else {
  6970. hide(getProgress(id));
  6971. hide(getSize(id));
  6972. hide(getDelete(id));
  6973. hide(getRetry(id));
  6974. hide(getPause(id));
  6975. hide(getContinue(id));
  6976. if (isCancelDisabled) {
  6977. this.hideCancel(id);
  6978. }
  6979. thumb = getThumbnail(id);
  6980. if (thumb && !thumb.src) {
  6981. cachedWaitingForThumbnailImg.then(function(waitingImg) {
  6982. thumb.src = waitingImg.src;
  6983. if (waitingImg.style.maxHeight && waitingImg.style.maxWidth) {
  6984. qq(thumb).css({
  6985. maxHeight: waitingImg.style.maxHeight,
  6986. maxWidth: waitingImg.style.maxWidth
  6987. });
  6988. }
  6989. show(thumb);
  6990. });
  6991. }
  6992. }
  6993. },
  6994. addFileToCache: function(id, name, prependInfo, hideForever) {
  6995. this.addFile(id, name, prependInfo, hideForever, true);
  6996. },
  6997. addCacheToDom: function() {
  6998. fileList.appendChild(fileBatch.content);
  6999. fileBatch.content = document.createDocumentFragment();
  7000. fileBatch.map = {};
  7001. },
  7002. removeFile: function(id) {
  7003. qq(getFile(id)).remove();
  7004. },
  7005. getFileId: function(el) {
  7006. var currentNode = el;
  7007. if (currentNode) {
  7008. while (currentNode.getAttribute(FILE_ID_ATTR) == null) {
  7009. currentNode = currentNode.parentNode;
  7010. }
  7011. return parseInt(currentNode.getAttribute(FILE_ID_ATTR));
  7012. }
  7013. },
  7014. getFileList: function() {
  7015. return fileList;
  7016. },
  7017. markFilenameEditable: function(id) {
  7018. var filename = getFilename(id);
  7019. filename && qq(filename).addClass(options.classes.editable);
  7020. },
  7021. updateFilename: function(id, name) {
  7022. var filenameEl = getFilename(id);
  7023. if (filenameEl) {
  7024. qq(filenameEl).setText(name);
  7025. filenameEl.setAttribute("title", name);
  7026. }
  7027. },
  7028. hideFilename: function(id) {
  7029. hide(getFilename(id));
  7030. },
  7031. showFilename: function(id) {
  7032. show(getFilename(id));
  7033. },
  7034. isFileName: function(el) {
  7035. return qq(el).hasClass(selectorClasses.file);
  7036. },
  7037. getButton: function() {
  7038. return options.button || getTemplateEl(container, selectorClasses.button);
  7039. },
  7040. hideDropProcessing: function() {
  7041. hide(getDropProcessing());
  7042. },
  7043. showDropProcessing: function() {
  7044. show(getDropProcessing());
  7045. },
  7046. getDropZone: function() {
  7047. return getTemplateEl(container, selectorClasses.drop);
  7048. },
  7049. isEditFilenamePossible: function() {
  7050. return isEditElementsExist;
  7051. },
  7052. hideRetry: function(id) {
  7053. hide(getRetry(id));
  7054. },
  7055. isRetryPossible: function() {
  7056. return isRetryElementExist;
  7057. },
  7058. showRetry: function(id) {
  7059. show(getRetry(id));
  7060. },
  7061. getFileContainer: function(id) {
  7062. return getFile(id);
  7063. },
  7064. showEditIcon: function(id) {
  7065. var icon = getEditIcon(id);
  7066. icon && qq(icon).addClass(options.classes.editable);
  7067. },
  7068. isHiddenForever: function(id) {
  7069. return qq(getFile(id)).hasClass(HIDDEN_FOREVER_CLASS);
  7070. },
  7071. hideEditIcon: function(id) {
  7072. var icon = getEditIcon(id);
  7073. icon && qq(icon).removeClass(options.classes.editable);
  7074. },
  7075. isEditIcon: function(el) {
  7076. return qq(el).hasClass(selectorClasses.editNameIcon, true);
  7077. },
  7078. getEditInput: function(id) {
  7079. return getTemplateEl(getFile(id), selectorClasses.editFilenameInput);
  7080. },
  7081. isEditInput: function(el) {
  7082. return qq(el).hasClass(selectorClasses.editFilenameInput, true);
  7083. },
  7084. updateProgress: function(id, loaded, total) {
  7085. var bar = getProgress(id), percent;
  7086. if (bar && total > 0) {
  7087. percent = Math.round(loaded / total * 100);
  7088. if (percent === 100) {
  7089. hide(bar);
  7090. } else {
  7091. show(bar);
  7092. }
  7093. setProgressBarWidth(id, percent);
  7094. }
  7095. },
  7096. updateTotalProgress: function(loaded, total) {
  7097. this.updateProgress(null, loaded, total);
  7098. },
  7099. hideProgress: function(id) {
  7100. var bar = getProgress(id);
  7101. bar && hide(bar);
  7102. },
  7103. hideTotalProgress: function() {
  7104. this.hideProgress();
  7105. },
  7106. resetProgress: function(id) {
  7107. setProgressBarWidth(id, 0);
  7108. this.hideTotalProgress(id);
  7109. },
  7110. resetTotalProgress: function() {
  7111. this.resetProgress();
  7112. },
  7113. showCancel: function(id) {
  7114. if (!isCancelDisabled) {
  7115. var cancel = getCancel(id);
  7116. cancel && qq(cancel).removeClass(options.classes.hide);
  7117. }
  7118. },
  7119. hideCancel: function(id) {
  7120. hide(getCancel(id));
  7121. },
  7122. isCancel: function(el) {
  7123. return qq(el).hasClass(selectorClasses.cancel, true);
  7124. },
  7125. allowPause: function(id) {
  7126. show(getPause(id));
  7127. hide(getContinue(id));
  7128. },
  7129. uploadPaused: function(id) {
  7130. this.setStatusText(id, options.text.paused);
  7131. this.allowContinueButton(id);
  7132. hide(getSpinner(id));
  7133. },
  7134. hidePause: function(id) {
  7135. hide(getPause(id));
  7136. },
  7137. isPause: function(el) {
  7138. return qq(el).hasClass(selectorClasses.pause, true);
  7139. },
  7140. isContinueButton: function(el) {
  7141. return qq(el).hasClass(selectorClasses.continueButton, true);
  7142. },
  7143. allowContinueButton: function(id) {
  7144. show(getContinue(id));
  7145. hide(getPause(id));
  7146. },
  7147. uploadContinued: function(id) {
  7148. this.setStatusText(id, "");
  7149. this.allowPause(id);
  7150. show(getSpinner(id));
  7151. },
  7152. showDeleteButton: function(id) {
  7153. show(getDelete(id));
  7154. },
  7155. hideDeleteButton: function(id) {
  7156. hide(getDelete(id));
  7157. },
  7158. isDeleteButton: function(el) {
  7159. return qq(el).hasClass(selectorClasses.deleteButton, true);
  7160. },
  7161. isRetry: function(el) {
  7162. return qq(el).hasClass(selectorClasses.retry, true);
  7163. },
  7164. updateSize: function(id, text) {
  7165. var size = getSize(id);
  7166. if (size) {
  7167. show(size);
  7168. qq(size).setText(text);
  7169. }
  7170. },
  7171. setStatusText: function(id, text) {
  7172. var textEl = getTemplateEl(getFile(id), selectorClasses.statusText);
  7173. if (textEl) {
  7174. if (text == null) {
  7175. qq(textEl).clearText();
  7176. } else {
  7177. qq(textEl).setText(text);
  7178. }
  7179. }
  7180. },
  7181. hideSpinner: function(id) {
  7182. qq(getFile(id)).removeClass(IN_PROGRESS_CLASS);
  7183. hide(getSpinner(id));
  7184. },
  7185. showSpinner: function(id) {
  7186. qq(getFile(id)).addClass(IN_PROGRESS_CLASS);
  7187. show(getSpinner(id));
  7188. },
  7189. generatePreview: function(id, optFileOrBlob, customResizeFunction) {
  7190. if (!this.isHiddenForever(id)) {
  7191. thumbGenerationQueue.push({
  7192. id: id,
  7193. customResizeFunction: customResizeFunction,
  7194. optFileOrBlob: optFileOrBlob
  7195. });
  7196. !thumbnailQueueMonitorRunning && generateNextQueuedPreview();
  7197. }
  7198. },
  7199. updateThumbnail: function(id, thumbnailUrl, showWaitingImg, customResizeFunction) {
  7200. if (!this.isHiddenForever(id)) {
  7201. thumbGenerationQueue.push({
  7202. customResizeFunction: customResizeFunction,
  7203. update: true,
  7204. id: id,
  7205. thumbnailUrl: thumbnailUrl,
  7206. showWaitingImg: showWaitingImg
  7207. });
  7208. !thumbnailQueueMonitorRunning && generateNextQueuedPreview();
  7209. }
  7210. },
  7211. hasDialog: function(type) {
  7212. return qq.supportedFeatures.dialogElement && !!getDialog(type);
  7213. },
  7214. showDialog: function(type, message, defaultValue) {
  7215. var dialog = getDialog(type), messageEl = getTemplateEl(dialog, selectorClasses.dialogMessage), inputEl = dialog.getElementsByTagName("INPUT")[0], cancelBtn = getTemplateEl(dialog, selectorClasses.dialogCancelButton), okBtn = getTemplateEl(dialog, selectorClasses.dialogOkButton), promise = new qq.Promise(), closeHandler = function() {
  7216. cancelBtn.removeEventListener("click", cancelClickHandler);
  7217. okBtn && okBtn.removeEventListener("click", okClickHandler);
  7218. promise.failure();
  7219. }, cancelClickHandler = function() {
  7220. cancelBtn.removeEventListener("click", cancelClickHandler);
  7221. dialog.close();
  7222. }, okClickHandler = function() {
  7223. dialog.removeEventListener("close", closeHandler);
  7224. okBtn.removeEventListener("click", okClickHandler);
  7225. dialog.close();
  7226. promise.success(inputEl && inputEl.value);
  7227. };
  7228. dialog.addEventListener("close", closeHandler);
  7229. cancelBtn.addEventListener("click", cancelClickHandler);
  7230. okBtn && okBtn.addEventListener("click", okClickHandler);
  7231. if (inputEl) {
  7232. inputEl.value = defaultValue;
  7233. }
  7234. messageEl.textContent = message;
  7235. dialog.showModal();
  7236. return promise;
  7237. }
  7238. });
  7239. };
  7240. qq.UiEventHandler = function(s, protectedApi) {
  7241. "use strict";
  7242. var disposer = new qq.DisposeSupport(), spec = {
  7243. eventType: "click",
  7244. attachTo: null,
  7245. onHandled: function(target, event) {}
  7246. };
  7247. qq.extend(this, {
  7248. addHandler: function(element) {
  7249. addHandler(element);
  7250. },
  7251. dispose: function() {
  7252. disposer.dispose();
  7253. }
  7254. });
  7255. function addHandler(element) {
  7256. disposer.attach(element, spec.eventType, function(event) {
  7257. event = event || window.event;
  7258. var target = event.target || event.srcElement;
  7259. spec.onHandled(target, event);
  7260. });
  7261. }
  7262. qq.extend(protectedApi, {
  7263. getFileIdFromItem: function(item) {
  7264. return item.qqFileId;
  7265. },
  7266. getDisposeSupport: function() {
  7267. return disposer;
  7268. }
  7269. });
  7270. qq.extend(spec, s);
  7271. if (spec.attachTo) {
  7272. addHandler(spec.attachTo);
  7273. }
  7274. };
  7275. qq.FileButtonsClickHandler = function(s) {
  7276. "use strict";
  7277. var inheritedInternalApi = {}, spec = {
  7278. templating: null,
  7279. log: function(message, lvl) {},
  7280. onDeleteFile: function(fileId) {},
  7281. onCancel: function(fileId) {},
  7282. onRetry: function(fileId) {},
  7283. onPause: function(fileId) {},
  7284. onContinue: function(fileId) {},
  7285. onGetName: function(fileId) {}
  7286. }, buttonHandlers = {
  7287. cancel: function(id) {
  7288. spec.onCancel(id);
  7289. },
  7290. retry: function(id) {
  7291. spec.onRetry(id);
  7292. },
  7293. deleteButton: function(id) {
  7294. spec.onDeleteFile(id);
  7295. },
  7296. pause: function(id) {
  7297. spec.onPause(id);
  7298. },
  7299. continueButton: function(id) {
  7300. spec.onContinue(id);
  7301. }
  7302. };
  7303. function examineEvent(target, event) {
  7304. qq.each(buttonHandlers, function(buttonType, handler) {
  7305. var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1), fileId;
  7306. if (spec.templating["is" + firstLetterCapButtonType](target)) {
  7307. fileId = spec.templating.getFileId(target);
  7308. qq.preventDefault(event);
  7309. spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
  7310. handler(fileId);
  7311. return false;
  7312. }
  7313. });
  7314. }
  7315. qq.extend(spec, s);
  7316. spec.eventType = "click";
  7317. spec.onHandled = examineEvent;
  7318. spec.attachTo = spec.templating.getFileList();
  7319. qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
  7320. };
  7321. qq.FilenameClickHandler = function(s) {
  7322. "use strict";
  7323. var inheritedInternalApi = {}, spec = {
  7324. templating: null,
  7325. log: function(message, lvl) {},
  7326. classes: {
  7327. file: "qq-upload-file",
  7328. editNameIcon: "qq-edit-filename-icon"
  7329. },
  7330. onGetUploadStatus: function(fileId) {},
  7331. onGetName: function(fileId) {}
  7332. };
  7333. qq.extend(spec, s);
  7334. function examineEvent(target, event) {
  7335. if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) {
  7336. var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId);
  7337. if (status === qq.status.SUBMITTED) {
  7338. spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
  7339. qq.preventDefault(event);
  7340. inheritedInternalApi.handleFilenameEdit(fileId, target, true);
  7341. }
  7342. }
  7343. }
  7344. spec.eventType = "click";
  7345. spec.onHandled = examineEvent;
  7346. qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
  7347. };
  7348. qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) {
  7349. "use strict";
  7350. var spec = {
  7351. templating: null,
  7352. onGetUploadStatus: function(fileId) {},
  7353. log: function(message, lvl) {}
  7354. };
  7355. if (!inheritedInternalApi) {
  7356. inheritedInternalApi = {};
  7357. }
  7358. function handleInputFocus(target, event) {
  7359. if (spec.templating.isEditInput(target)) {
  7360. var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId);
  7361. if (status === qq.status.SUBMITTED) {
  7362. spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId));
  7363. inheritedInternalApi.handleFilenameEdit(fileId, target);
  7364. }
  7365. }
  7366. }
  7367. spec.eventType = "focusin";
  7368. spec.onHandled = handleInputFocus;
  7369. qq.extend(spec, s);
  7370. qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi));
  7371. };
  7372. qq.FilenameInputFocusHandler = function(spec) {
  7373. "use strict";
  7374. spec.eventType = "focus";
  7375. spec.attachTo = null;
  7376. qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {}));
  7377. };
  7378. qq.FilenameEditHandler = function(s, inheritedInternalApi) {
  7379. "use strict";
  7380. var spec = {
  7381. templating: null,
  7382. log: function(message, lvl) {},
  7383. onGetUploadStatus: function(fileId) {},
  7384. onGetName: function(fileId) {},
  7385. onSetName: function(fileId, newName) {},
  7386. onEditingStatusChange: function(fileId, isEditing) {}
  7387. };
  7388. function getFilenameSansExtension(fileId) {
  7389. var filenameSansExt = spec.onGetName(fileId), extIdx = filenameSansExt.lastIndexOf(".");
  7390. if (extIdx > 0) {
  7391. filenameSansExt = filenameSansExt.substr(0, extIdx);
  7392. }
  7393. return filenameSansExt;
  7394. }
  7395. function getOriginalExtension(fileId) {
  7396. var origName = spec.onGetName(fileId);
  7397. return qq.getExtension(origName);
  7398. }
  7399. function handleNameUpdate(newFilenameInputEl, fileId) {
  7400. var newName = newFilenameInputEl.value, origExtension;
  7401. if (newName !== undefined && qq.trimStr(newName).length > 0) {
  7402. origExtension = getOriginalExtension(fileId);
  7403. if (origExtension !== undefined) {
  7404. newName = newName + "." + origExtension;
  7405. }
  7406. spec.onSetName(fileId, newName);
  7407. }
  7408. spec.onEditingStatusChange(fileId, false);
  7409. }
  7410. function registerInputBlurHandler(inputEl, fileId) {
  7411. inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() {
  7412. handleNameUpdate(inputEl, fileId);
  7413. });
  7414. }
  7415. function registerInputEnterKeyHandler(inputEl, fileId) {
  7416. inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) {
  7417. var code = event.keyCode || event.which;
  7418. if (code === 13) {
  7419. handleNameUpdate(inputEl, fileId);
  7420. }
  7421. });
  7422. }
  7423. qq.extend(spec, s);
  7424. spec.attachTo = spec.templating.getFileList();
  7425. qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi));
  7426. qq.extend(inheritedInternalApi, {
  7427. handleFilenameEdit: function(id, target, focusInput) {
  7428. var newFilenameInputEl = spec.templating.getEditInput(id);
  7429. spec.onEditingStatusChange(id, true);
  7430. newFilenameInputEl.value = getFilenameSansExtension(id);
  7431. if (focusInput) {
  7432. newFilenameInputEl.focus();
  7433. }
  7434. registerInputBlurHandler(newFilenameInputEl, id);
  7435. registerInputEnterKeyHandler(newFilenameInputEl, id);
  7436. }
  7437. });
  7438. };
  7439. })(window);
  7440. //# sourceMappingURL=fine-uploader.js.map