CCMain.m 261 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCControlCenterTransferCell.h"
  28. #import <OCCommunicationLib/OCActivity.h>
  29. #import <OCCommunicationLib/OCNotifications.h>
  30. #import <OCCommunicationLib/OCNotificationsAction.h>
  31. #import <OCCommunicationLib/OCFrameworkConstants.h>
  32. #import <OCCommunicationLib/OCCapabilities.h>
  33. #import "CTAssetCheckmark.h"
  34. #ifdef CUSTOM_BUILD
  35. #import "Custom.h"
  36. #else
  37. #import "Nextcloud-Swift.h"
  38. #endif
  39. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  40. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  41. #define alertCreateFolder 1
  42. #define alertCreateFolderCrypto 2
  43. #define alertRename 3
  44. #define alertOfflineFolder 4
  45. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  46. {
  47. CCMetadata *_metadataSegue;
  48. CCMetadata *_metadata;
  49. BOOL _isRoot;
  50. BOOL _isViewDidLoad;
  51. BOOL _isOfflineServerUrl;
  52. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  53. BOOL _isSelectedMode;
  54. NSMutableArray *_selectedMetadatas;
  55. NSMutableArray *_queueSelector;
  56. NSUInteger _numSelectedMetadatas;
  57. UIImageView *_ImageTitleHomeCryptoCloud;
  58. UIView *_reMenuBackgroundView;
  59. UITapGestureRecognizer *_singleFingerTap;
  60. NSString *_directoryGroupBy;
  61. NSString *_directoryOrder;
  62. NSUInteger _failedAttempts;
  63. NSDate *_lockUntilDate;
  64. NSString *_fatherPermission;
  65. UIRefreshControl *_refreshControl;
  66. UIDocumentInteractionController *_docController;
  67. CCHud *_hud;
  68. CCHud *_hudDeterminate;
  69. // Datasource
  70. CCSectionDataSourceMetadata *_sectionDataSource;
  71. NSDate *_dateReadDataSource;
  72. // Search
  73. BOOL _isSearchMode;
  74. NSString *_searchFileName;
  75. NSArray *_searchResultMetadatas;
  76. }
  77. @end
  78. @implementation CCMain
  79. #pragma --------------------------------------------------------------------------------------------
  80. #pragma mark ===== Init =====
  81. #pragma --------------------------------------------------------------------------------------------
  82. - (id)initWithCoder:(NSCoder *)aDecoder
  83. {
  84. if (self = [super initWithCoder:aDecoder]) {
  85. _directoryOrder = [CCUtility getOrderSettings];
  86. _directoryGroupBy = [CCUtility getGroupBySettings];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [CCMetadata new];
  101. _metadataSegue = [CCMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedMetadatas = [NSMutableArray new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSArray new];
  110. _searchFileName = @"";
  111. // delegate
  112. self.tableView.delegate = self;
  113. self.tableView.tableFooterView = [UIView new];
  114. self.tableView.separatorColor = COLOR_SEPARATOR_TABLE;
  115. self.searchController.delegate = self;
  116. self.searchController.searchBar.delegate = self;
  117. [[CCNetworking sharedNetworking] settingDelegate:self];
  118. // Custom Cell
  119. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  120. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  121. // long press recognizer TableView
  122. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  123. [self.tableView addGestureRecognizer:longPressRecognizer];
  124. // Pull-to-Refresh
  125. [self createRefreshControl];
  126. // Register for 3D Touch Previewing if available
  127. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  128. {
  129. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  130. }
  131. // Back Button
  132. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  133. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController] style:UIBarButtonItemStylePlain target:nil action:nil];
  134. // reMenu Background
  135. _reMenuBackgroundView = [[UIView alloc] init];
  136. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  137. // if this is not Main (the Main uses inizializeMain)
  138. if (_isRoot == NO && app.activeAccount.length > 0) {
  139. // Settings this folder & delegate & Loading datasource
  140. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  141. // Load Datasource
  142. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  143. // Read Folder
  144. [self readFolderWithForced:NO serverUrl:_serverUrl];
  145. }
  146. // Title
  147. [self setTitle];
  148. // List Transfers
  149. //app.controlCenter = (CCControlCenter *)self.navigationController;
  150. // Search
  151. self.definesPresentationContext = YES;
  152. self.searchController.searchResultsUpdater = self;
  153. self.searchController.dimsBackgroundDuringPresentation = NO;
  154. self.tableView.tableHeaderView = self.searchController.searchBar;
  155. self.searchController.searchBar.barTintColor = COLOR_SEPARATOR_TABLE;
  156. [self.searchController.searchBar sizeToFit];
  157. if ([CCCoreData getServerVersionActiveAccount:app.activeAccount] >= 12) {
  158. if (_isRoot)
  159. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  160. else
  161. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  162. } else {
  163. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  164. }
  165. }
  166. // Apparirà
  167. - (void)viewWillAppear:(BOOL)animated
  168. {
  169. [super viewWillAppear:animated];
  170. // test
  171. if (app.activeAccount.length == 0)
  172. return;
  173. // Settings this folder & delegate & Loading datasource
  174. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  175. [[CCNetworking sharedNetworking] settingDelegate:self];
  176. // Color
  177. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  178. [CCAspect aspectTabBar:self.tabBarController.tabBar hidden:NO];
  179. // Menu e Bar
  180. [self createReMainMenu];
  181. [self createReSelectMenu];
  182. if (_isSelectedMode)
  183. [self setUINavigationBarSelected];
  184. else
  185. [self setUINavigationBarDefault];
  186. // Plus Button
  187. [app plusButtonVisibile:true];
  188. }
  189. // E' arrivato
  190. - (void)viewDidAppear:(BOOL)animated
  191. {
  192. [super viewDidAppear:animated];
  193. // Active Main
  194. app.activeMain = self;
  195. // Test viewDidLoad
  196. if (_isViewDidLoad) {
  197. _isViewDidLoad = NO;
  198. } else {
  199. if (app.activeAccount.length > 0) {
  200. // Load Datasource
  201. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  202. // Read Folder
  203. [self readFolderWithForced:NO serverUrl:_serverUrl];
  204. }
  205. }
  206. // Title
  207. [self setTitle];
  208. // cancell Progress
  209. [self.navigationController cancelCCProgress];
  210. }
  211. - (void)viewWillDisappear:(BOOL)animated
  212. {
  213. [super viewWillDisappear:animated];
  214. // Close MainMenu & SelectMenu
  215. if (app.reMainMenu.isOpen || app.reSelectMenu.isOpen) {
  216. [app.reMainMenu close];
  217. [app.reSelectMenu close];
  218. }
  219. // Close Menu Logo
  220. [CCMenu dismissMenu];
  221. }
  222. - (void)didReceiveMemoryWarning
  223. {
  224. [super didReceiveMemoryWarning];
  225. // Dispose of any resources that can be recreated.
  226. }
  227. - (BOOL)prefersStatusBarHidden
  228. {
  229. return NO;
  230. }
  231. // detect scroll for remove keyboard in search mode
  232. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  233. {
  234. if (_isSearchMode && scrollView == self.tableView) {
  235. [self.searchController.searchBar endEditing:YES];
  236. }
  237. }
  238. #pragma --------------------------------------------------------------------------------------------
  239. #pragma mark ===== Initizlize Mail =====
  240. #pragma --------------------------------------------------------------------------------------------
  241. - (void)initializeMain:(NSNotification *)notification
  242. {
  243. _directoryGroupBy = nil;
  244. _directoryOrder = nil;
  245. _dateReadDataSource = nil;
  246. // test
  247. if (app.activeAccount.length == 0)
  248. return;
  249. if ([app.listMainVC count] == 0 || _isRoot) {
  250. // This is Root
  251. _isRoot = YES;
  252. // Crypto Mode
  253. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  254. app.isCryptoCloudMode = NO;
  255. } else {
  256. app.isCryptoCloudMode = YES;
  257. }
  258. // go Home
  259. [self.navigationController popToRootViewControllerAnimated:NO];
  260. // Remove search mode
  261. [self cancelSearchBar];
  262. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  263. _isFolderEncrypted = NO;
  264. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  265. // add list
  266. [app.listMainVC setObject:self forKey:_serverUrl];
  267. // setting Networking
  268. [[CCNetworking sharedNetworking] settingDelegate:self];
  269. [[CCNetworking sharedNetworking] settingAccount];
  270. // populate shared Link & User variable
  271. [CCCoreData populateSharesVariableFromDBActiveAccount:app.activeAccount sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup];
  272. // Load Datasource
  273. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  274. // Load Folder
  275. [self readFolderWithForced:NO serverUrl:_serverUrl];
  276. // Load photo datasorce
  277. if (app.activePhotosCameraUpload)
  278. [app.activePhotosCameraUpload reloadDatasourceForced];
  279. // remove all of detail
  280. if (app.activeDetail)
  281. [app.activeDetail removeAllView];
  282. // remove all Notification Messages
  283. [app.listOfNotifications removeAllObjects];
  284. // home main
  285. app.homeMain = self;
  286. // Initializations
  287. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  288. [app applicationInitialized];
  289. });
  290. } else {
  291. // reload datasource
  292. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  293. }
  294. }
  295. #pragma --------------------------------------------------------------------------------------------
  296. #pragma mark ===== AlertView =====
  297. #pragma --------------------------------------------------------------------------------------------
  298. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  299. {
  300. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  301. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  302. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  303. if (alertView.tag == alertRename && buttonIndex == 1) {
  304. if ([_metadata.model isEqualToString:@"note"]) {
  305. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  306. } else {
  307. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  308. }
  309. }
  310. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  311. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  312. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  313. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  314. [self performSelector:@selector(reloadDatasource) withObject:nil];
  315. }
  316. }
  317. // accept only number char > 0
  318. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  319. {
  320. /* Retrieve a text field at an index -
  321. raises NSRangeException when textFieldIndex is out-of-bounds.
  322. The field at index 0 will be the first text field
  323. (the single field or the login field),
  324. The field at index 1 will be the password field. */
  325. /*
  326. 1> Get the Text Field in alertview
  327. 2> Get the text of that Text Field
  328. 3> Verify that text length
  329. 4> return YES or NO Based on the length
  330. */
  331. if (alertView.tag == alertOfflineFolder) return YES;
  332. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  333. }
  334. #pragma --------------------------------------------------------------------------------------------
  335. #pragma mark ===== Graphic Window =====
  336. #pragma --------------------------------------------------------------------------------------------
  337. - (void)createRefreshControl
  338. {
  339. _refreshControl = [UIRefreshControl new];
  340. _refreshControl.tintColor = COLOR_REFRESH_CONTROL;
  341. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  342. [self setRefreshControl:_refreshControl];
  343. }
  344. - (void)deleteRefreshControl
  345. {
  346. [_refreshControl endRefreshing];
  347. self.refreshControl = nil;
  348. }
  349. - (void)refreshControlTarget
  350. {
  351. [self readFolderWithForced:YES serverUrl:_serverUrl];
  352. // Actuate `Peek` feedback (weak boom)
  353. AudioServicesPlaySystemSound(1519);
  354. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  355. }
  356. - (void)setTitle
  357. {
  358. // PopGesture in progress [swipe gesture to switch between views]
  359. if (app.controlCenter.isPopGesture)
  360. return;
  361. // Color text self.navigationItem.title
  362. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  363. if (_isSelectedMode) {
  364. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  365. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  366. self.navigationItem.titleView = nil;
  367. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  368. } else {
  369. // we are in home : LOGO BRAND
  370. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  371. self.navigationItem.title = nil;
  372. if ([app.reachability isReachable] == NO) _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationControllerOffline]];
  373. else _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController]];
  374. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  375. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  376. [singleTap setNumberOfTapsRequired:1];
  377. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  378. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  379. } else {
  380. self.navigationItem.title = _titleMain;
  381. }
  382. }
  383. }
  384. - (void)setTitleBackgroundTableView
  385. {
  386. if ([_sectionDataSource.allRecordsDataSource count] == 0) {
  387. [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_", nil)];
  388. } else {
  389. [self setTitleBackgroundTableView:nil];
  390. }
  391. }
  392. - (void)setTitleBackgroundTableView:(NSString *)title
  393. {
  394. if (title) {
  395. // message if table is empty
  396. UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
  397. if ([app.reachability isReachable] == NO) {
  398. messageLabel.text = NSLocalizedString(@"_comm_erro_pull_down_", nil);
  399. messageLabel.textColor = COLOR_TEXT_NO_CONNECTION;
  400. messageLabel.font = [UIFont systemFontOfSize:14];
  401. } else {
  402. messageLabel.text = NSLocalizedString(title ,nil);
  403. messageLabel.textColor = COLOR_TEXT_NO_CONNECTION;
  404. messageLabel.font = [UIFont systemFontOfSize:14];
  405. }
  406. messageLabel.numberOfLines = 0;
  407. messageLabel.textAlignment = NSTextAlignmentCenter;
  408. [messageLabel sizeToFit];
  409. [self.tableView reloadData];
  410. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  411. self.tableView.backgroundView = messageLabel;
  412. } else {
  413. [self.tableView setBackgroundView:nil];
  414. self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
  415. }
  416. }
  417. - (void)setUINavigationBarDefault
  418. {
  419. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  420. UIBarButtonItem *buttonMore, *buttonNotification;
  421. // =
  422. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_more] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  423. buttonMore.enabled = true;
  424. // <
  425. self.navigationController.navigationBar.hidden = NO;
  426. // Notification
  427. if ([app.listOfNotifications count] > 0) {
  428. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_notification] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  429. buttonNotification.tintColor = COLOR_NAVIGATIONBAR_TEXT;
  430. buttonNotification.enabled = true;
  431. }
  432. if (buttonNotification)
  433. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  434. else
  435. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  436. self.navigationItem.leftBarButtonItem = nil;
  437. // close Menu
  438. [app.reSelectMenu close];
  439. [app.reMainMenu close];
  440. }
  441. - (void)setUINavigationBarSelected
  442. {
  443. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  444. UIImage *icon = [UIImage imageNamed:image_more];
  445. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  446. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  447. self.navigationItem.leftBarButtonItem = leftButton;
  448. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  449. }
  450. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  451. {
  452. // close the menus
  453. if (app.reMainMenu.isOpen)
  454. [app.reMainMenu close];
  455. if (app.reSelectMenu.isOpen)
  456. [app.reSelectMenu close];
  457. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  458. }];
  459. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  460. }
  461. - (void)cancelSelect
  462. {
  463. [self tableViewSelect:NO];
  464. }
  465. #pragma --------------------------------------------------------------------------------------------
  466. #pragma mark ===== Document Picker =====
  467. #pragma --------------------------------------------------------------------------------------------
  468. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  469. {
  470. NSLog(@"Cancelled");
  471. }
  472. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  473. {
  474. NSLog(@"Cancelled");
  475. }
  476. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  477. {
  478. documentPicker.delegate = self;
  479. [self presentViewController:documentPicker animated:YES completion:nil];
  480. }
  481. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  482. {
  483. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  484. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  485. __block NSError *error;
  486. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  487. NSString *fileName = [url lastPathComponent];
  488. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  489. NSData *data = [NSData dataWithContentsOfURL:newURL];
  490. if (data && error == nil) {
  491. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  492. // Upload File
  493. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  494. } else {
  495. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  496. }
  497. } else {
  498. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  499. }
  500. }];
  501. }
  502. }
  503. - (void)openImportDocumentPicker
  504. {
  505. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  506. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  507. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  508. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  509. documentProviderMenu.delegate = self;
  510. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  511. }
  512. #pragma --------------------------------------------------------------------------------------------
  513. #pragma mark ===== Assets Picker =====
  514. #pragma --------------------------------------------------------------------------------------------
  515. - (void)openAssetsPickerController
  516. {
  517. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  518. checkmark.tintColor = COLOR_BRAND;
  519. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  520. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  521. [CCAspect aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  522. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  523. dispatch_async(dispatch_get_main_queue(), ^{
  524. // init picker
  525. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  526. // set delegate
  527. picker.delegate = self;
  528. // to show selection order
  529. //picker.showsSelectionIndex = YES;
  530. // to present picker as a form sheet in iPad
  531. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  532. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  533. // present picker
  534. [self presentViewController:picker animated:YES completion:nil];
  535. });
  536. }];
  537. }
  538. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  539. {
  540. [picker dismissViewControllerAnimated:YES completion:^{
  541. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  542. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  543. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  544. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  545. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  546. [self presentViewController:navigationController animated:YES completion:nil];
  547. }];
  548. }
  549. #pragma --------------------------------------------------------------------------------------------
  550. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  551. #pragma --------------------------------------------------------------------------------------------
  552. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  553. {
  554. // evitiamo il rimando della eventuale photo e/o video
  555. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  556. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  557. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  558. }
  559. }
  560. #pragma --------------------------------------------------------------------------------------------
  561. #pragma mark ===== UnZipFile =====
  562. #pragma --------------------------------------------------------------------------------------------
  563. - (void)unZipFile:(NSString *)fileID
  564. {
  565. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  566. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  567. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  568. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  569. dispatch_async(dispatch_get_main_queue(), ^{
  570. float progress = (float) entryNumber / (float)total;
  571. [_hudDeterminate progress:progress];
  572. });
  573. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  574. dispatch_async(dispatch_get_main_queue(), ^{
  575. [_hudDeterminate hideHud];
  576. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  577. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  578. });
  579. }];
  580. });
  581. }
  582. #pragma --------------------------------------------------------------------------------------------
  583. #pragma mark ===== Create New (OpenModel) =====
  584. #pragma --------------------------------------------------------------------------------------------
  585. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  586. {
  587. UIViewController *viewController;
  588. NSString *fileName, *uuid, *fileID, *serverUrl;
  589. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  590. [self.tableView deselectRowAtIndexPath:index animated:NO];
  591. if (isnew) {
  592. fileName = nil;
  593. uuid = [CCUtility getUUID];
  594. fileID = nil;
  595. serverUrl = _serverUrl;
  596. } else {
  597. fileName = _metadata.fileName;
  598. uuid = _metadata.uuid;
  599. fileID = _metadata.fileID;
  600. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  601. }
  602. if ([tipo isEqualToString:@"cartadicredito"])
  603. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  604. if ([tipo isEqualToString:@"bancomat"])
  605. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  606. if ([tipo isEqualToString:@"contocorrente"])
  607. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  608. if ([tipo isEqualToString:@"accountweb"])
  609. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  610. if ([tipo isEqualToString:@"patenteguida"])
  611. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  612. if ([tipo isEqualToString:@"cartaidentita"])
  613. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  614. if ([tipo isEqualToString:@"passaporto"])
  615. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  616. if ([tipo isEqualToString:@"note"]) {
  617. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  618. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  619. [self presentViewController:navigationController animated:YES completion:nil];
  620. } else {
  621. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  622. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  623. [self presentViewController:navigationController animated:YES completion:nil];
  624. }
  625. }
  626. // New folder or new photo or video
  627. - (void)returnCreate:(NSInteger)type
  628. {
  629. switch (type) {
  630. /* PLAIN */
  631. case k_returnCreateFolderPlain: {
  632. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  633. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  634. alertView.tag = alertCreateFolder;
  635. [alertView show];
  636. }
  637. break;
  638. case k_returnCreateFotoVideoPlain: {
  639. _isPickerCriptate = false;
  640. [self openAssetsPickerController];
  641. }
  642. break;
  643. case k_returnCreateFilePlain: {
  644. _isPickerCriptate = false;
  645. [self openImportDocumentPicker];
  646. }
  647. break;
  648. /* ENCRYPTED */
  649. case k_returnCreateFolderEncrypted: {
  650. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  651. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  652. alertView.tag = alertCreateFolderCrypto;
  653. [alertView show];
  654. }
  655. break;
  656. case k_returnCreateFotoVideoEncrypted: {
  657. _isPickerCriptate = true;
  658. [self openAssetsPickerController];
  659. }
  660. break;
  661. case k_returnCreateFileEncrypted: {
  662. _isPickerCriptate = true;
  663. [self openImportDocumentPicker];
  664. }
  665. break;
  666. /* UTILITY */
  667. case k_returnNote:
  668. [self openModel:@"note" isNew:true];
  669. break;
  670. case k_returnAccountWeb:
  671. [self openModel:@"accountweb" isNew:true];
  672. break;
  673. /* BANK */
  674. case k_returnCartaDiCredito:
  675. [self openModel:@"cartadicredito" isNew:true];
  676. break;
  677. case k_returnBancomat:
  678. [self openModel:@"bancomat" isNew:true];
  679. break;
  680. case k_returnContoCorrente:
  681. [self openModel:@"contocorrente" isNew:true];
  682. break;
  683. /* DOCUMENT */
  684. case k_returnPatenteGuida:
  685. [self openModel:@"patenteguida" isNew:true];
  686. break;
  687. case k_returnCartaIdentita:
  688. [self openModel:@"cartaidentita" isNew:true];
  689. break;
  690. case k_returnPassaporto:
  691. [self openModel:@"passaporto" isNew:true];
  692. break;
  693. }
  694. }
  695. #pragma --------------------------------------------------------------------------------------------
  696. #pragma mark ===== Save selected File =====
  697. #pragma --------------------------------------------------------------------------------------------
  698. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  699. {
  700. if (error)
  701. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  702. else
  703. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  704. }
  705. - (void)saveSelectedFiles
  706. {
  707. NSLog(@"[LOG] Start download selected files ...");
  708. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  709. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  710. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  711. for (CCMetadata *metadata in metadatas) {
  712. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  713. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  714. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  715. }
  716. }
  717. [_hud hideHud];
  718. });
  719. [self tableViewSelect:NO];
  720. }
  721. #pragma --------------------------------------------------------------------------------------------
  722. #pragma mark ===== Change Password =====
  723. #pragma --------------------------------------------------------------------------------------------
  724. - (void) loginSuccess:(NSInteger)loginType
  725. {
  726. [self readFolderWithForced:YES serverUrl:_serverUrl];
  727. }
  728. - (void)changePasswordAccount
  729. {
  730. CCLogin *loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  731. loginVC.delegate = self;
  732. loginVC.loginType = loginModifyPasswordUser;
  733. [self presentViewController:loginVC animated:YES completion:nil];
  734. }
  735. #pragma mark -
  736. #pragma --------------------------------------------------------------------------------------------
  737. #pragma mark ===== Peek & Pop =====
  738. #pragma --------------------------------------------------------------------------------------------
  739. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  740. {
  741. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  742. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  743. if (metadata.thumbnailExists && !metadata.cryptated) {
  744. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  745. if (cell) {
  746. previewingContext.sourceRect = cell.frame;
  747. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  748. vc.delegate = self;
  749. vc.metadata = metadata;
  750. return vc;
  751. }
  752. }
  753. return nil;
  754. }
  755. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  756. {
  757. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  758. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  759. }
  760. #pragma mark -
  761. #pragma --------------------------------------------------------------------------------------------
  762. #pragma mark ==== Activity ====
  763. #pragma --------------------------------------------------------------------------------------------
  764. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  765. {
  766. for (OCActivity *activity in listOfActivity) {
  767. [CCCoreData addActivity:activity account:app.activeAccount];
  768. }
  769. // Reload Activity Data Source
  770. [app.controlCenterActivity reloadDatasource];
  771. }
  772. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  773. {
  774. }
  775. #pragma --------------------------------------------------------------------------------------------
  776. #pragma mark ==== Notification ====
  777. #pragma --------------------------------------------------------------------------------------------
  778. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  779. {
  780. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  781. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  782. // Order by date
  783. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  784. OCNotifications *notification1 = obj1, *notification2 = obj2;
  785. return [notification2.date compare: notification1.date];
  786. }];
  787. // verify if listOfNotifications is changed
  788. NSString *old = @"", *new = @"";
  789. for (OCNotifications *notification in listOfNotifications)
  790. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  791. for (OCNotifications *notification in appDelegate.listOfNotifications)
  792. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  793. if (![new isEqualToString:old]) {
  794. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  795. // reload Notification view
  796. dispatch_async(dispatch_get_main_queue(), ^{
  797. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  798. });
  799. }
  800. // Update NavigationBar
  801. if (!_isSelectedMode) {
  802. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  803. }
  804. });
  805. }
  806. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  807. {
  808. // Update NavigationBar
  809. if (!_isSelectedMode)
  810. [self setUINavigationBarDefault];
  811. }
  812. - (void)viewNotification
  813. {
  814. if ([app.listOfNotifications count] > 0) {
  815. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  816. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  817. [self presentViewController:notificationVC animated:YES completion:nil];
  818. }
  819. }
  820. #pragma --------------------------------------------------------------------------------------------
  821. #pragma mark ==== Request Server ====
  822. #pragma --------------------------------------------------------------------------------------------
  823. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  824. {
  825. [CCCoreData setUserProfileActiveAccount:metadataNet.account userProfile:userProfile];
  826. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  827. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  828. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  829. if (avatar)
  830. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  831. else
  832. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  833. });
  834. }
  835. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  836. {
  837. app.capabilities = capabilities;
  838. [CCCoreData setServerVersionActiveAccount:app.activeAccount versionMajor:capabilities.versionMajor versionMinor:capabilities.versionMinor versionMicro:capabilities.versionMicro];
  839. // Search placeholder
  840. if (capabilities.versionMajor >= 12) {
  841. if (_isRoot)
  842. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  843. else
  844. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  845. } else {
  846. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  847. }
  848. }
  849. - (void)getFeaturesSupportedByServerSuccess:(BOOL)hasCapabilitiesSupport hasForbiddenCharactersSupport:(BOOL)hasForbiddenCharactersSupport hasShareSupport:(BOOL)hasShareSupport hasShareeSupport:(BOOL)hasShareeSupport
  850. {
  851. app.hasServerCapabilitiesSupport = hasCapabilitiesSupport;
  852. app.hasServerForbiddenCharactersSupport = hasForbiddenCharactersSupport;
  853. app.hasServerShareSupport = hasShareSupport;
  854. app.hasServerShareeSupport = hasShareeSupport;
  855. if (hasShareSupport || hasShareeSupport)
  856. [self requestSharedByServer];
  857. }
  858. - (void)getInfoServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  859. {
  860. if (errorCode == 401)
  861. [self changePasswordAccount];
  862. }
  863. - (void)requestServerInformation
  864. {
  865. // test
  866. if (app.activeAccount.length == 0)
  867. return;
  868. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  869. [app.sharesID removeAllObjects];
  870. app.hasServerForbiddenCharactersSupport = YES;
  871. app.hasServerShareSupport = YES;
  872. metadataNet.action = actionGetFeaturesSuppServer;
  873. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  874. metadataNet.action = actionGetCapabilities;
  875. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  876. metadataNet.action = actionGetNotificationServer;
  877. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  878. metadataNet.action = actionGetUserProfile;
  879. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  880. metadataNet.action = actionGetActivityServer;
  881. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  882. }
  883. #pragma --------------------------------------------------------------------------------------------
  884. #pragma mark ==== Download Thumbnail Delegate ====
  885. #pragma --------------------------------------------------------------------------------------------
  886. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  887. {
  888. __block CCCellMain *cell;
  889. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  890. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  891. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  892. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  893. if (cell.fileImageView.image == nil) {
  894. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  895. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  896. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  897. });
  898. }
  899. }
  900. }
  901. #pragma --------------------------------------------------------------------------------------------
  902. #pragma mark ==== Download ====
  903. #pragma --------------------------------------------------------------------------------------------
  904. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  905. {
  906. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  907. // File do not exists on server, remove in local
  908. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  909. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  910. }
  911. if ([selector isEqualToString:selectorLoadViewImage]) {
  912. dispatch_async(dispatch_get_main_queue(), ^{
  913. // Updating Detail
  914. if (app.activeDetail)
  915. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  916. // Updating Photos
  917. if (app.activePhotosCameraUpload)
  918. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  919. });
  920. } else {
  921. if (errorCode != kCFURLErrorCancelled)
  922. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  923. }
  924. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  925. }
  926. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  927. {
  928. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  929. if (metadata == nil) return;
  930. // reload
  931. if ([selector isEqualToString:selectorReload]) {
  932. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  933. }
  934. // Synchronized
  935. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  936. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  937. }
  938. // add Favorite
  939. if ([selector isEqualToString:selectorAddFavorite]) {
  940. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  941. }
  942. // add Offline
  943. if ([selector isEqualToString:selectorAddOffline]) {
  944. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  945. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  946. }
  947. // encrypted file
  948. if ([selector isEqualToString:selectorEncryptFile]) {
  949. [self encryptedFile:metadata];
  950. }
  951. // decrypted file
  952. if ([selector isEqualToString:selectorDecryptFile]) {
  953. [self decryptedFile:metadata];
  954. }
  955. // open View File
  956. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  957. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  958. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  959. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  960. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  961. selector = selectorOpenIn;
  962. } else {
  963. _metadataSegue = metadata;
  964. _metadataSegue.sessionSelector = selector;
  965. if ([self shouldPerformSegue:serverUrl])
  966. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  967. }
  968. }
  969. // addLocal
  970. if ([selector isEqualToString:selectorAddLocal]) {
  971. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  972. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  973. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  974. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  975. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  976. }
  977. // Open with...
  978. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  979. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  980. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  981. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  982. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  983. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  984. _docController.delegate = self;
  985. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  986. }
  987. // Save to Photo Album
  988. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  989. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  990. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  991. // evitiamo il rimando photo
  992. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  993. UIImage *image = [UIImage imageWithContentsOfFile:file];
  994. if (image)
  995. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  996. else
  997. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  998. }
  999. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1000. // we avoid the cross-reference video
  1001. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  1002. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1003. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1004. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1005. } else {
  1006. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1007. }
  1008. }
  1009. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1010. }
  1011. // Copy File
  1012. if ([selector isEqualToString:selectorLoadCopy]) {
  1013. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1014. [self copyFileToPasteboard:metadata];
  1015. }
  1016. // download and view a template
  1017. if ([selector isEqualToString:selectorLoadModelView]) {
  1018. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1019. [self openModel:metadata.model isNew:false];
  1020. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1021. }
  1022. //download file plist
  1023. if ([selector isEqualToString:selectorLoadPlist]) {
  1024. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1025. long countSelectorLoadPlist = 0;
  1026. for (NSOperation *operation in [app.netQueue operations]) {
  1027. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1028. countSelectorLoadPlist++;
  1029. }
  1030. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1031. dispatch_async(dispatch_get_main_queue(), ^{
  1032. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1033. });
  1034. }
  1035. }
  1036. //selectorLoadViewImage
  1037. if ([selector isEqualToString:selectorLoadViewImage]) {
  1038. dispatch_async(dispatch_get_main_queue(), ^{
  1039. // Detail
  1040. if (app.activeDetail)
  1041. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1042. // Photos
  1043. if (app.activePhotosCameraUpload)
  1044. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1045. });
  1046. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1047. }
  1048. // if exists postselector call self with selectorPost
  1049. if ([selectorPost length] > 0)
  1050. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1051. }
  1052. - (void)downloadSelectedFiles
  1053. {
  1054. NSLog(@"[LOG] Start download selected files ...");
  1055. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1056. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1057. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1058. for (CCMetadata *metadata in selectedMetadatas) {
  1059. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1060. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1061. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1062. }
  1063. }
  1064. [_hud hideHud];
  1065. });
  1066. [self tableViewSelect:NO];
  1067. }
  1068. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1069. {
  1070. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1071. for (TableMetadata *recordMetadata in records) {
  1072. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1073. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1074. metadataNet.action = actionDownloadFile;
  1075. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1076. metadataNet.downloadData = NO;
  1077. metadataNet.downloadPlist = YES;
  1078. metadataNet.selector = selectorLoadPlist;
  1079. metadataNet.serverUrl = serverUrl;
  1080. metadataNet.session = k_download_session_foreground;
  1081. metadataNet.taskStatus = k_taskStatusResume;
  1082. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1083. }
  1084. }
  1085. }
  1086. #pragma --------------------------------------------------------------------------------------------
  1087. #pragma mark ===== Upload new Photos/Videos =====
  1088. #pragma --------------------------------------------------------------------------------------------
  1089. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1090. {
  1091. // Automatic upload
  1092. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1093. [app loadTableAutomaticUploadForSelector:selector];
  1094. // Read File test do not exists
  1095. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1096. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1097. // reUpload
  1098. if (metadata)
  1099. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1100. }
  1101. // Print error
  1102. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1103. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1104. }
  1105. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1106. }
  1107. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1108. {
  1109. // Automatic upload
  1110. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1111. [app loadTableAutomaticUploadForSelector:selector];
  1112. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1113. [self readFolderWithForced:YES serverUrl:serverUrl];
  1114. } else {
  1115. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1116. }
  1117. }
  1118. //
  1119. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1120. //
  1121. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1122. {
  1123. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  1124. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1125. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1126. });
  1127. }
  1128. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1129. {
  1130. NSArray *assets = [arguments objectAtIndex:0];
  1131. NSString *serverUrl = [arguments objectAtIndex:1];
  1132. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1133. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1134. NSString * session = [arguments objectAtIndex:4];
  1135. // remove title (graphics)
  1136. [self setTitleBackgroundTableView:nil];
  1137. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1138. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1139. // Create if request the folder for Photos
  1140. if ((useSubFolder || [serverUrl isEqualToString:folderPhotos]) && [_serverUrl isEqualToString:serverUrl] == NO){
  1141. if(![app.activePhotosCameraUpload automaticCreateFolder:folderPhotos]) {
  1142. [_hud hideHud];
  1143. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1144. return;
  1145. }
  1146. }
  1147. // Create if request the subfolders
  1148. if (useSubFolder) {
  1149. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  1150. if(![app.activePhotosCameraUpload automaticCreateFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  1151. [_hud hideHud];
  1152. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1153. return;
  1154. }
  1155. }
  1156. }
  1157. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1158. for (PHAsset *asset in assets) {
  1159. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1160. NSDate *assetDate = asset.creationDate;
  1161. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1162. // Create serverUrl if use sub folder
  1163. if (useSubFolder) {
  1164. [formatter setDateFormat:@"yyyy"];
  1165. NSString *yearString = [formatter stringFromDate:assetDate];
  1166. [formatter setDateFormat:@"MM"];
  1167. NSString *monthString = [formatter stringFromDate:assetDate];
  1168. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1169. }
  1170. // Check if is in upload
  1171. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1172. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1173. if ([isRecordInSessions count] > 0) {
  1174. // next upload
  1175. continue;
  1176. } else {
  1177. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1178. metadataNet.action = actionReadFile;
  1179. metadataNet.identifier = asset.localIdentifier;
  1180. metadataNet.cryptated = cryptated;
  1181. metadataNet.fileName = fileName;
  1182. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1183. metadataNet.session = session;
  1184. metadataNet.selector = selectorReadFileUploadFile;
  1185. metadataNet.serverUrl = serverUrl;
  1186. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1187. }
  1188. }
  1189. [_hud hideHud];
  1190. }
  1191. #pragma --------------------------------------------------------------------------------------------
  1192. #pragma mark ==== Read File ====
  1193. #pragma --------------------------------------------------------------------------------------------
  1194. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1195. {
  1196. // UploadFile
  1197. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1198. // File not exists
  1199. if (errorCode == 404) {
  1200. metadataNet.action = actionUploadAsset;
  1201. metadataNet.errorCode = 0;
  1202. metadataNet.selector = selectorUploadFile;
  1203. metadataNet.selectorPost = nil;
  1204. metadataNet.taskStatus = k_taskStatusResume;
  1205. if ([metadataNet.session containsString:@"wwan"])
  1206. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1207. else
  1208. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1209. } else {
  1210. // error ho many retry befor notification and go to on next asses
  1211. if (metadataNet.errorRetry < 3) {
  1212. // Retry read file
  1213. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1214. } else {
  1215. // STOP check file, view message error
  1216. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1217. }
  1218. }
  1219. }
  1220. }
  1221. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1222. {
  1223. // UploadFile
  1224. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1225. metadataNet.action = actionUploadAsset;
  1226. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1227. metadataNet.selector = selectorUploadFile;
  1228. metadataNet.selectorPost = nil;
  1229. metadataNet.taskStatus = k_taskStatusResume;
  1230. if ([metadataNet.session containsString:@"wwan"])
  1231. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1232. else
  1233. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1234. }
  1235. }
  1236. #pragma --------------------------------------------------------------------------------------------
  1237. #pragma mark ==== Read Folder ====
  1238. #pragma --------------------------------------------------------------------------------------------
  1239. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1240. {
  1241. // verify active user
  1242. TableAccount *record = [CCCoreData getActiveAccount];
  1243. [_hud hideHud];
  1244. [_refreshControl endRefreshing];
  1245. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1246. if (message && [record.account isEqualToString:metadataNet.account])
  1247. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1248. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1249. if (errorCode == 401)
  1250. [self changePasswordAccount];
  1251. }
  1252. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1253. {
  1254. // verify active user
  1255. TableAccount *record = [CCCoreData getActiveAccount];
  1256. if (![record.account isEqualToString:metadataNet.account])
  1257. return;
  1258. // save father e update permission
  1259. if(!_isSearchMode)
  1260. _fatherPermission = permissions;
  1261. NSArray *recordsInSessions;
  1262. if (_isSearchMode) {
  1263. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", metadataNet.account] context:nil];
  1264. } else {
  1265. [CCCoreData updateDirectoryEtagServerUrl:metadataNet.serverUrl etag:etag activeAccount:metadataNet.account];
  1266. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadataNet.directoryID]];
  1267. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (session != NULL) AND (session != '')", metadataNet.account, metadataNet.directoryID] context:nil];
  1268. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1269. }
  1270. for (CCMetadata *metadata in metadatas) {
  1271. // Delete Record only in Search Mode
  1272. if (_isSearchMode)
  1273. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileID = %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1274. // type of file
  1275. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1276. // if crypto do not insert
  1277. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1278. // verify if the record encrypted has plist + crypto
  1279. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1280. BOOL isCryptoComplete = NO;
  1281. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1282. for (CCMetadata *completeMetadata in metadatas) {
  1283. if (completeMetadata.cryptated == NO) continue;
  1284. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1285. isCryptoComplete = YES;
  1286. break;
  1287. }
  1288. }
  1289. if (isCryptoComplete == NO) continue;
  1290. }
  1291. // verify if the record is in download/upload progress
  1292. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1293. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1294. // is in Upload
  1295. if (metadataDB.session && [metadataDB.session containsString:@"upload"]) {
  1296. NSString *sessionID = metadataDB.sessionID;
  1297. // rename SessionID -> fileID
  1298. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1299. metadataDB.session = @"";
  1300. metadataDB.date = metadata.date;
  1301. metadataDB.fileID = metadata.fileID;
  1302. metadataDB.rev = metadata.fileID;
  1303. metadataDB.sessionError = @"";
  1304. metadataDB.sessionID = @"";
  1305. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1306. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1307. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1308. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1309. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1310. continue;
  1311. }
  1312. // download in progress
  1313. if (metadataDB.session && [metadataDB.session containsString:@"download"])
  1314. continue;
  1315. }
  1316. // end test, insert in CoreData
  1317. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1318. }
  1319. // read plist
  1320. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1321. // File is changed ??
  1322. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1323. if (!_isSearchMode)
  1324. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount synchronize:NO];
  1325. });
  1326. // Search Mode
  1327. if (_isSearchMode)
  1328. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1329. // this is the same directory
  1330. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1331. // reload
  1332. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1333. // stoprefresh
  1334. [_refreshControl endRefreshing];
  1335. // Enable change user
  1336. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1337. [_hud hideHud];
  1338. }
  1339. }
  1340. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1341. {
  1342. [self setTitleBackgroundTableView:nil];
  1343. // init control
  1344. if (!serverUrl || !app.activeAccount)
  1345. return;
  1346. // Search Mode
  1347. if (_isSearchMode) {
  1348. if (forced) {
  1349. [CCCoreData clearDateReadDirectory:serverUrl activeAccount:app.activeAccount];
  1350. _searchFileName = @""; // forced reload searchg
  1351. }
  1352. [self updateSearchResultsForSearchController:self.searchController];
  1353. return;
  1354. }
  1355. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1356. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1357. if (_refreshControl.isRefreshing == NO)
  1358. [_hud visibleIndeterminateHud];
  1359. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1360. metadataNet.action = actionReadFolder;
  1361. metadataNet.date = [NSDate date];
  1362. metadataNet.directoryID = directoryID;
  1363. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1364. metadataNet.selector = selectorReadFolder;
  1365. metadataNet.serverUrl = serverUrl;
  1366. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1367. } else {
  1368. if ([_sectionDataSource.allRecordsDataSource count] == 0) [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_",nil)];
  1369. else [self setTitleBackgroundTableView:nil];
  1370. }
  1371. }
  1372. #pragma mark -
  1373. #pragma --------------------------------------------------------------------------------------------
  1374. #pragma mark ===== Search =====
  1375. #pragma --------------------------------------------------------------------------------------------
  1376. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1377. {
  1378. _isSearchMode = YES;
  1379. [self deleteRefreshControl];
  1380. NSString *fileName = [CCUtility removeForbiddenCharacters:searchController.searchBar.text hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1381. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1382. _searchFileName = fileName;
  1383. NSString *depth = @"1";
  1384. if ([[CCUtility getHomeServerUrlActiveUrl:app.activeUrl] isEqualToString:_serverUrl])
  1385. depth = @"infinity";
  1386. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:depth delegate:self];
  1387. }
  1388. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1389. [self reloadDatasource];
  1390. }
  1391. }
  1392. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1393. {
  1394. [self cancelSearchBar];
  1395. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1396. }
  1397. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1398. {
  1399. _searchFileName = @"";
  1400. if (message)
  1401. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1402. }
  1403. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1404. {
  1405. _searchResultMetadatas = [[NSArray alloc] initWithArray:metadatas];
  1406. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1407. }
  1408. - (void)cancelSearchBar
  1409. {
  1410. if (self.searchController.active) {
  1411. [self.searchController setActive:NO];
  1412. [self createRefreshControl];
  1413. _isSearchMode = NO;
  1414. _searchFileName = @"";
  1415. _dateReadDataSource = nil;
  1416. _searchResultMetadatas = [NSArray new];
  1417. [self reloadDatasource];
  1418. }
  1419. }
  1420. #pragma mark -
  1421. #pragma --------------------------------------------------------------------------------------------
  1422. #pragma mark ===== Delete File or Folder =====
  1423. #pragma --------------------------------------------------------------------------------------------
  1424. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1425. {
  1426. [self deleteFileOrFolderSuccess:metadataNet];
  1427. }
  1428. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1429. {
  1430. [_queueSelector removeObject:metadataNet.selector];
  1431. if ([_queueSelector count] == 0) {
  1432. [_hud hideHud];
  1433. if (_isSearchMode)
  1434. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1435. else
  1436. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1437. // next
  1438. if ([_selectedMetadatas count] > 0) {
  1439. [_selectedMetadatas removeObjectAtIndex:0];
  1440. if ([_selectedMetadatas count] > 0)
  1441. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1442. }
  1443. }
  1444. }
  1445. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1446. {
  1447. if (metadata.cryptated) {
  1448. [_queueSelector addObject:selectorDeleteCrypto];
  1449. [_queueSelector addObject:selectorDeletePlist];
  1450. } else {
  1451. [_queueSelector addObject:selectorDelete];
  1452. }
  1453. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1454. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1455. }
  1456. - (void)deleteSelectionFile
  1457. {
  1458. [_selectedMetadatas removeAllObjects];
  1459. [_queueSelector removeAllObjects];
  1460. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1461. _numSelectedMetadatas = [_selectedMetadatas count];
  1462. if ([_selectedMetadatas count] > 0)
  1463. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1464. [self tableViewSelect:NO];
  1465. }
  1466. - (void)deleteFile
  1467. {
  1468. [_selectedMetadatas removeAllObjects];
  1469. [_queueSelector removeAllObjects];
  1470. _numSelectedMetadatas = 1;
  1471. [_selectedMetadatas addObject:_metadata];
  1472. if ([_selectedMetadatas count] > 0)
  1473. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1474. [self tableViewSelect:NO];
  1475. }
  1476. #pragma --------------------------------------------------------------------------------------------
  1477. #pragma mark ===== Rename / Move =====
  1478. #pragma --------------------------------------------------------------------------------------------
  1479. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1480. {
  1481. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1482. }
  1483. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1484. {
  1485. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1486. }
  1487. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1488. {
  1489. CCTemplates *templates = [[CCTemplates alloc] init];
  1490. CCCrypto *crypto = [[CCCrypto alloc] init];
  1491. NSMutableDictionary *field = [crypto getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1492. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1493. if (fileNameModel) {
  1494. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1495. metadataNet.action = actionUploadTemplate;
  1496. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1497. metadataNet.fileNamePrint = fileName;
  1498. metadataNet.rev = metadata.rev;
  1499. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1500. metadataNet.session = k_upload_session_foreground;
  1501. metadataNet.taskStatus = k_taskStatusResume;
  1502. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1503. metadataNet.selectorPost = selectorAddOffline;
  1504. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1505. }
  1506. }
  1507. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1508. {
  1509. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1510. [_hud hideHud];
  1511. if (message)
  1512. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1513. [_selectedMetadatas removeAllObjects];
  1514. [_queueSelector removeAllObjects];
  1515. }
  1516. }
  1517. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1518. {
  1519. [_queueSelector removeObject:metadataNet.selector];
  1520. if ([_queueSelector count] == 0) {
  1521. [_hud hideHud];
  1522. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1523. NSString *directoryID = metadataNet.directoryID;
  1524. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1525. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1526. // FILE -> Metadata
  1527. if (metadataNet.directory == NO) {
  1528. // move metadata
  1529. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1530. }
  1531. // DIRECTORY -> Directory - CCMetadata
  1532. if (metadataNet.directory == YES) {
  1533. // delete all dir / subdir
  1534. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1535. // delete all metadata and local file in dir / subdir
  1536. for (NSString *directoryIDDelete in directoryIDs)
  1537. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1538. // move metadata
  1539. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1540. // Add new directory
  1541. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1542. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1543. // Check Offline
  1544. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1545. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1546. }
  1547. // reload Datasource
  1548. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1549. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1550. else
  1551. [self reloadDatasource];
  1552. // Next file
  1553. [_selectedMetadatas removeObjectAtIndex:0];
  1554. [self moveFileOrFolder:metadataNet.serverUrlTo];
  1555. }
  1556. }
  1557. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1558. {
  1559. if ([_selectedMetadatas count] > 0) {
  1560. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1561. // Plain
  1562. if (metadata.cryptated == NO) {
  1563. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1564. metadataNet.action = actionMoveFileOrFolder;
  1565. metadataNet.directory = metadata.directory;
  1566. metadataNet.fileID = metadata.fileID;
  1567. metadataNet.directoryID = metadata.directoryID;
  1568. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1569. metadataNet.fileName = metadata.fileName;
  1570. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1571. metadataNet.fileNameTo = metadata.fileName;
  1572. metadataNet.rev = metadata.rev;
  1573. metadataNet.selector = selectorMove;
  1574. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1575. metadataNet.serverUrlTo = serverUrlTo;
  1576. [_queueSelector addObject:metadataNet.selector];
  1577. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1578. }
  1579. // cyptated
  1580. if (metadata.cryptated == YES) {
  1581. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1582. metadataNet.action = actionMoveFileOrFolder;
  1583. metadataNet.directory = metadata.directory;
  1584. metadataNet.fileID = metadata.fileID;
  1585. metadataNet.directoryID = metadata.directoryID;
  1586. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1587. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1588. metadataNet.rev = metadata.rev;
  1589. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1590. metadataNet.serverUrlTo = serverUrlTo;
  1591. // data
  1592. metadataNet.fileName = metadata.fileNameData;
  1593. metadataNet.fileNameTo = metadata.fileNameData;
  1594. metadataNet.selector = selectorMoveCrypto;
  1595. [_queueSelector addObject:metadataNet.selector];
  1596. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1597. // plist
  1598. metadataNet.fileName = metadata.fileName;
  1599. metadataNet.fileNameTo = metadata.fileName;
  1600. metadataNet.selector = selectorMovePlist;
  1601. [_queueSelector addObject:metadataNet.selector];
  1602. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1603. }
  1604. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1605. }
  1606. }
  1607. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1608. {
  1609. [_selectedMetadatas removeAllObjects];
  1610. [_queueSelector removeAllObjects];
  1611. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1612. _numSelectedMetadatas = [_selectedMetadatas count];
  1613. [self moveFileOrFolder:serverUrlTo];
  1614. [self tableViewSelect:NO];
  1615. }
  1616. - (void)moveOpenWindow:(NSArray *)indexPaths
  1617. {
  1618. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1619. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1620. viewController.delegate = self;
  1621. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1622. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1623. viewController.tintColor = COLOR_NAVIGATIONBAR_TEXT;
  1624. viewController.barTintColor = COLOR_NAVIGATIONBAR;
  1625. viewController.tintColorTitle = COLOR_NAVIGATIONBAR_TEXT;
  1626. viewController.networkingOperationQueue = app.netQueue;
  1627. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1628. [self presentViewController:navigationController animated:YES completion:nil];
  1629. }
  1630. #pragma --------------------------------------------------------------------------------------------
  1631. #pragma mark ===== Create folder =====
  1632. #pragma --------------------------------------------------------------------------------------------
  1633. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1634. {
  1635. [_hud hideHud];
  1636. if (message)
  1637. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1638. }
  1639. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1640. {
  1641. [_hud hideHud];
  1642. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1643. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1644. // Check Offline
  1645. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1646. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1647. // Load Folder or the Datasource
  1648. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1649. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1650. } else {
  1651. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1652. }
  1653. }
  1654. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1655. {
  1656. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1657. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1658. if (![fileNameFolder length]) return;
  1659. if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1660. else metadataNet.serverUrl = _serverUrl;
  1661. metadataNet.action = actionCreateFolder;
  1662. if (folderCameraUpload)
  1663. metadataNet.options = @"folderCameraUpload";
  1664. metadataNet.fileName = fileNameFolder;
  1665. metadataNet.selector = selectorCreateFolder;
  1666. metadataNet.selectorPost = selectorReadFolderForced;
  1667. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1668. if (!folderCameraUpload)
  1669. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1670. }
  1671. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1672. {
  1673. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1674. CCCrypto *crypto = [[CCCrypto alloc] init];
  1675. NSString *fileNamePlist;
  1676. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1677. if (![fileNameFolder length]) return;
  1678. NSString *title = [AESCrypt encrypt:fileNameFolder password:[crypto getKeyPasscode:[CCUtility getUUID]]];
  1679. fileNamePlist = [crypto createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1680. [crypto createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1681. // Create folder
  1682. metadataNet.action = actionCreateFolder;
  1683. metadataNet.fileName = fileNamePlist;
  1684. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1685. metadataNet.selector = selectorCreateFolder;
  1686. metadataNet.serverUrl = _serverUrl;
  1687. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1688. // upload plist file
  1689. metadataNet.action = actionUploadOnlyPlist;
  1690. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1691. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1692. metadataNet.selectorPost = selectorReadFolderForced;
  1693. metadataNet.serverUrl = _serverUrl;
  1694. metadataNet.session = k_upload_session_foreground;
  1695. metadataNet.taskStatus = k_taskStatusResume;
  1696. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1697. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1698. }
  1699. - (void)createFolderCameraUpload
  1700. {
  1701. [self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1702. }
  1703. #pragma --------------------------------------------------------------------------------------------
  1704. #pragma mark ===== Encrypted / Decrypted Folder =====
  1705. #pragma --------------------------------------------------------------------------------------------
  1706. - (void)encyptedDecryptedFolder
  1707. {
  1708. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1709. if (_metadata.cryptated) {
  1710. // DECRYPTED
  1711. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1712. //-------------------------- RENAME -------------------------------------------//
  1713. metadataNet.action = actionMoveFileOrFolder;
  1714. metadataNet.fileID = _metadata.fileID;
  1715. metadataNet.fileName = _metadata.fileNameData;
  1716. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1717. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1718. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1719. metadataNet.selector = selectorRename;
  1720. metadataNet.serverUrl = serverUrl;
  1721. metadataNet.serverUrlTo = serverUrl;
  1722. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1723. //-------------------------- DELETE -------------------------------------------//
  1724. metadataNet.action = actionDeleteFileDirectory;
  1725. metadataNet.fileID = _metadata.fileID;
  1726. metadataNet.fileName = _metadata.fileName;
  1727. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1728. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1729. metadataNet.selector = selectorDeletePlist;
  1730. metadataNet.selectorPost = selectorReadFolderForced;
  1731. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1732. } else {
  1733. // ENCRYPTED
  1734. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1735. CCCrypto *crypto = [[CCCrypto alloc] init];
  1736. // Create File Plist
  1737. NSString *fileNameCrypto = [crypto createFileDirectoryPlist:_metadata];
  1738. //-------------------------- RENAME -------------------------------------------//
  1739. metadataNet.action = actionMoveFileOrFolder;
  1740. metadataNet.fileID = _metadata.fileID;
  1741. metadataNet.fileName = _metadata.fileName;
  1742. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1743. metadataNet.fileNameTo = fileNameCrypto;
  1744. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1745. metadataNet.selector = selectorRename;
  1746. metadataNet.serverUrl = serverUrl;
  1747. metadataNet.serverUrlTo = serverUrl;
  1748. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1749. //-------------------------- UPLOAD -------------------------------------------//
  1750. metadataNet.action = actionUploadOnlyPlist;
  1751. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1752. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1753. metadataNet.selectorPost = selectorReadFolderForced;
  1754. metadataNet.serverUrl = serverUrl;
  1755. metadataNet.session = k_upload_session_foreground;
  1756. metadataNet.taskStatus = k_taskStatusResume;
  1757. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1758. }
  1759. }
  1760. #pragma --------------------------------------------------------------------------------------------
  1761. #pragma mark ===== Encrypted/Decrypted File =====
  1762. #pragma --------------------------------------------------------------------------------------------
  1763. - (void)encryptedSelectedFiles
  1764. {
  1765. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1766. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1767. for (CCMetadata *metadata in selectedMetadatas) {
  1768. if (metadata.cryptated == NO && metadata.directory == NO)
  1769. [metadatas addObject:metadata];
  1770. }
  1771. if ([metadatas count] > 0) {
  1772. NSLog(@"[LOG] Start encrypted selected files ...");
  1773. for (CCMetadata* metadata in metadatas) {
  1774. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1775. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1776. }
  1777. }
  1778. [self tableViewSelect:NO];
  1779. }
  1780. - (void)decryptedSelectedFiles
  1781. {
  1782. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1783. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1784. for (CCMetadata *metadata in selectedMetadatas) {
  1785. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1786. [metadatas addObject:metadata];
  1787. }
  1788. if ([metadatas count] > 0) {
  1789. NSLog(@"[LOG] Start decrypted selected files ...");
  1790. for (CCMetadata* metadata in metadatas) {
  1791. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1792. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1793. }
  1794. }
  1795. [self tableViewSelect:NO];
  1796. }
  1797. - (void)cmdEncryptedDecryptedFile
  1798. {
  1799. NSString *selector;
  1800. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1801. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1802. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1803. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1804. }
  1805. - (void)encryptedFile:(CCMetadata *)metadata
  1806. {
  1807. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1808. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1809. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1810. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1811. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1812. dispatch_async(dispatch_get_main_queue(), ^{
  1813. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1814. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1815. });
  1816. } else {
  1817. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1818. }
  1819. }
  1820. - (void)decryptedFile:(CCMetadata *)metadata
  1821. {
  1822. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1823. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1824. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1825. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1826. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1827. dispatch_async(dispatch_get_main_queue(), ^{
  1828. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1829. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1830. });
  1831. } else {
  1832. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1833. }
  1834. }
  1835. #pragma --------------------------------------------------------------------------------------------
  1836. #pragma mark ===== Progress & Task Button =====
  1837. #pragma --------------------------------------------------------------------------------------------
  1838. - (void)progressTask:(NSString *)fileID serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated progress:(float)progress;
  1839. {
  1840. // Check
  1841. if (!fileID)
  1842. return;
  1843. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1844. if (![serverUrl isEqualToString:_serverUrl])
  1845. return;
  1846. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1847. if (indexPath) {
  1848. CCControlCenterTransferCell *cell = (CCControlCenterTransferCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1849. if (cryptated) cell.progressView.progressTintColor = COLOR_CRYPTOCLOUD;
  1850. else cell.progressView.progressTintColor = COLOR_TEXT_ANTHRACITE;
  1851. cell.progressView.hidden = NO;
  1852. [cell.progressView setProgress:progress];
  1853. }
  1854. }
  1855. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1856. {
  1857. UITouch * touch = [[event allTouches] anyObject];
  1858. CGPoint location = [touch locationInView:self.tableView];
  1859. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1860. if (indexPath) {
  1861. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1862. if (metadata)
  1863. [self reloadTaskButton:metadata];
  1864. }
  1865. }
  1866. - (void)reloadTaskButton:(CCMetadata *)metadata
  1867. {
  1868. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1869. __block NSURLSessionTask *findTask;
  1870. // DOWNLOAD
  1871. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1872. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1873. for (NSURLSessionUploadTask *task in downloadTasks)
  1874. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1875. findTask = task;
  1876. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1877. [task cancel];
  1878. }
  1879. if (!findTask) {
  1880. dispatch_async(dispatch_get_main_queue(), ^{
  1881. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1882. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1883. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1884. });
  1885. }
  1886. }];
  1887. }
  1888. // UPLOAD
  1889. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1890. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1891. for (NSURLSessionUploadTask *task in uploadTasks)
  1892. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1893. findTask = task;
  1894. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1895. [task cancel];
  1896. }
  1897. if (!findTask) {
  1898. dispatch_async(dispatch_get_main_queue(), ^{
  1899. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1900. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1901. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1902. });
  1903. }
  1904. }];
  1905. }
  1906. }
  1907. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1908. {
  1909. UITouch * touch = [[event allTouches] anyObject];
  1910. CGPoint location = [touch locationInView:self.tableView];
  1911. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1912. if (indexPath) {
  1913. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1914. if (metadata)
  1915. [self cancelTaskButton:metadata reloadTable:YES];
  1916. }
  1917. }
  1918. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  1919. {
  1920. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1921. __block NSURLSessionTask *findTask;
  1922. // DOWNLOAD
  1923. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1924. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1925. for (NSURLSessionTask *task in downloadTasks)
  1926. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1927. findTask = task;
  1928. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1929. [task cancel];
  1930. }
  1931. if (!findTask) {
  1932. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1933. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1934. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1935. }
  1936. }];
  1937. }
  1938. // UPLOAD
  1939. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1940. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1941. for (NSURLSessionUploadTask *task in uploadTasks)
  1942. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1943. findTask = task;
  1944. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1945. [task cancel];
  1946. }
  1947. if (!findTask) {
  1948. dispatch_async(dispatch_get_main_queue(), ^{
  1949. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1950. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1951. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1952. });
  1953. }
  1954. }];
  1955. }
  1956. }
  1957. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1958. {
  1959. UITouch * touch = [[event allTouches] anyObject];
  1960. CGPoint location = [touch locationInView:self.tableView];
  1961. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1962. if (indexPath) {
  1963. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1964. if (metadata)
  1965. [self stopTaskButton:metadata];
  1966. }
  1967. }
  1968. - (void)stopTaskButton:(CCMetadata *)metadata
  1969. {
  1970. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1971. __block NSURLSessionTask *findTask;
  1972. // UPLOAD
  1973. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1974. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1975. for (NSURLSessionUploadTask *task in uploadTasks)
  1976. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1977. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1978. findTask = task;
  1979. [task cancel];
  1980. }
  1981. if (!findTask) {
  1982. dispatch_async(dispatch_get_main_queue(), ^{
  1983. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1984. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1985. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1986. });
  1987. }
  1988. }];
  1989. }
  1990. }
  1991. #pragma --------------------------------------------------------------------------------------------
  1992. #pragma mark ===== Shared =====
  1993. #pragma --------------------------------------------------------------------------------------------
  1994. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1995. {
  1996. [_hud hideHud];
  1997. // change account ?
  1998. TableAccount *record = [CCCoreData getActiveAccount];
  1999. if([record.account isEqualToString:metadataNet.account] == NO)
  2000. return;
  2001. [CCCoreData updateShare:items sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount activeUrl:app.activeUrl];
  2002. if (openWindow) {
  2003. if (_shareOC) {
  2004. [_shareOC reloadData];
  2005. } else {
  2006. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2007. // Apriamo la view
  2008. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2009. _shareOC.delegate = self;
  2010. _shareOC.metadata = metadata;
  2011. _shareOC.serverUrl = metadataNet.serverUrl;
  2012. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2013. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2014. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2015. [self presentViewController:_shareOC animated:YES completion:nil];
  2016. }
  2017. }
  2018. [self tableViewReload];
  2019. }
  2020. - (void)requestSharedByServer
  2021. {
  2022. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2023. metadataNet.action = actionReadShareServer;
  2024. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2025. }
  2026. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2027. {
  2028. [_hud hideHud];
  2029. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2030. if (_shareOC)
  2031. [_shareOC reloadData];
  2032. [self tableViewReload];
  2033. if (errorCode == 401)
  2034. [self changePasswordAccount];
  2035. }
  2036. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2037. {
  2038. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2039. metadataNet.action = actionShare;
  2040. metadataNet.fileID = metadata.fileID;
  2041. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2042. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2043. metadataNet.password = password;
  2044. metadataNet.selector = selectorShare;
  2045. metadataNet.serverUrl = serverUrl;
  2046. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2047. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2048. }
  2049. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2050. {
  2051. [_hud hideHud];
  2052. // rimuoviamo la condivisione da db
  2053. [CCCoreData unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount];
  2054. if (_shareOC)
  2055. [_shareOC reloadData];
  2056. [self tableViewReload];
  2057. }
  2058. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2059. {
  2060. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2061. metadataNet.action = actionUnShare;
  2062. metadataNet.fileID = metadata.fileID;
  2063. metadataNet.fileName = metadata.fileName;
  2064. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2065. metadataNet.selector = selectorUnshare;
  2066. metadataNet.serverUrl = serverUrl;
  2067. metadataNet.share = share;
  2068. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2069. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2070. }
  2071. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2072. {
  2073. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2074. metadataNet.action = actionUpdateShare;
  2075. metadataNet.fileID = metadata.fileID;
  2076. metadataNet.expirationTime = expirationTime;
  2077. metadataNet.password = password;
  2078. metadataNet.selector = selectorUpdateShare;
  2079. metadataNet.serverUrl = serverUrl;
  2080. metadataNet.share = share;
  2081. metadataNet.sharePermission = permission;
  2082. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2083. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2084. }
  2085. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2086. {
  2087. [_hud hideHud];
  2088. if (_shareOC)
  2089. [_shareOC reloadUserAndGroup:items];
  2090. }
  2091. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2092. {
  2093. [_hud hideHud];
  2094. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2095. }
  2096. - (void)getUserAndGroup:(NSString *)find
  2097. {
  2098. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2099. metadataNet.action = actionGetUserAndGroup;
  2100. metadataNet.options = find;
  2101. metadataNet.selector = selectorGetUserAndGroup;
  2102. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2103. [_hud visibleIndeterminateHud];
  2104. }
  2105. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2106. {
  2107. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2108. metadataNet.action = actionShareWith;
  2109. metadataNet.fileID = metadata.fileID;
  2110. metadataNet.directoryID = directoryID;
  2111. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2112. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2113. metadataNet.serverUrl = serverUrl;
  2114. metadataNet.selector = selectorShare;
  2115. metadataNet.share = user;
  2116. metadataNet.shareeType = shareeType;
  2117. metadataNet.sharePermission = permission;
  2118. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2119. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2120. }
  2121. - (void)openWindowShare:(CCMetadata *)metadata
  2122. {
  2123. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2124. metadataNet.action = actionReadShareServer;
  2125. metadataNet.fileID = metadata.fileID;
  2126. metadataNet.fileName = metadata.fileName;
  2127. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2128. metadataNet.selector = selectorOpenWindowShare;
  2129. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2130. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2131. [_hud visibleIndeterminateHud];
  2132. }
  2133. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2134. {
  2135. CGPoint location = [tapGesture locationInView:self.tableView];
  2136. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2137. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2138. if (metadata)
  2139. [self openWindowShare:metadata];
  2140. }
  2141. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2142. {
  2143. CGPoint location = [tapGesture locationInView:self.tableView];
  2144. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2145. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2146. if (metadata) {
  2147. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2148. vc.metadata = metadata;
  2149. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2150. [self presentViewController:vc animated:YES completion:nil];
  2151. }
  2152. }
  2153. #pragma --------------------------------------------------------------------------------------------
  2154. #pragma mark ===== Favorite =====
  2155. #pragma --------------------------------------------------------------------------------------------
  2156. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2157. {
  2158. [CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2159. _dateReadDataSource = nil;
  2160. if (_isSearchMode)
  2161. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2162. else
  2163. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2164. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2165. if (metadata.directory && metadata.favorite) {
  2166. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2167. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2168. }
  2169. }
  2170. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2171. {
  2172. }
  2173. - (void)addFavorite:(CCMetadata *)metadata
  2174. {
  2175. if (metadata.directory) {
  2176. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2177. } else {
  2178. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2179. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2180. }
  2181. }
  2182. - (void)removeFavorite:(CCMetadata *)metadata
  2183. {
  2184. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2185. }
  2186. #pragma --------------------------------------------------------------------------------------------
  2187. #pragma mark ===== Offline =====
  2188. #pragma --------------------------------------------------------------------------------------------
  2189. - (void)addOffline:(CCMetadata *)metadata
  2190. {
  2191. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2192. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2193. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2194. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2195. }
  2196. - (void)removeOffline:(CCMetadata *)metadata
  2197. {
  2198. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2199. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2200. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2201. }
  2202. #pragma --------------------------------------------------------------------------------------------
  2203. #pragma mark ===== Local =====
  2204. #pragma --------------------------------------------------------------------------------------------
  2205. - (void)addLocal:(CCMetadata *)metadata
  2206. {
  2207. if (metadata.errorPasscode || !metadata.uuid) return;
  2208. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2209. if ([metadata.type isEqualToString: k_metadataType_file])
  2210. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2211. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2212. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2213. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  2214. }
  2215. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2216. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2217. }
  2218. #pragma --------------------------------------------------------------------------------------------
  2219. #pragma mark ===== Reload =====
  2220. #pragma --------------------------------------------------------------------------------------------
  2221. - (void)reloadFile:(CCMetadata *)metadata
  2222. {
  2223. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2224. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2225. }
  2226. #pragma --------------------------------------------------------------------------------------------
  2227. #pragma mark ===== Open in... =====
  2228. #pragma --------------------------------------------------------------------------------------------
  2229. - (void)openIn:(CCMetadata *)metadata
  2230. {
  2231. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2232. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2233. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2234. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2235. }
  2236. #pragma --------------------------------------------------------------------------------------------
  2237. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2238. #pragma --------------------------------------------------------------------------------------------
  2239. - (void)orderTable:(NSString *)order
  2240. {
  2241. [CCUtility setOrderSettings:order];
  2242. // Clear data-read of DataSource
  2243. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2244. // new menu
  2245. [self createReMainMenu];
  2246. }
  2247. - (void)ascendingTable:(BOOL)ascending
  2248. {
  2249. [CCUtility setAscendingSettings:ascending];
  2250. // Clear data-read of DataSource
  2251. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2252. // new menu
  2253. [self createReMainMenu];
  2254. }
  2255. - (void)directoryOnTop:(BOOL)directoryOnTop
  2256. {
  2257. [CCUtility setDirectoryOnTop:directoryOnTop];
  2258. // Clear data-read of DataSource
  2259. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2260. // new menu
  2261. [self createReMainMenu];
  2262. }
  2263. - (void)tableGroupBy:(NSString *)groupBy
  2264. {
  2265. [CCUtility setGroupBySettings:groupBy];
  2266. // Clear data-read of DataSource
  2267. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2268. // new menu
  2269. [self createReMainMenu];
  2270. }
  2271. #pragma --------------------------------------------------------------------------------------------
  2272. #pragma mark ==== Menu LOGO ====
  2273. #pragma --------------------------------------------------------------------------------------------
  2274. - (void)menuLogo
  2275. {
  2276. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2277. return;
  2278. #ifndef NO_MULTIUSER
  2279. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [CCCoreData countTableAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2280. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  2281. return;
  2282. }
  2283. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2284. NSMutableArray *menuArray = [[NSMutableArray alloc] init];
  2285. for (TableAccount *record in listTableAccount) {
  2286. if ([record.account isEqualToString:app.activeAccount]) continue;
  2287. CCMenuItem *item = [[CCMenuItem alloc] init];
  2288. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2289. item.argument = record.account;
  2290. item.image = [UIImage imageNamed:image_Nextcloud];
  2291. item.target = self;
  2292. item.action = @selector(changeDefaultAccount:);
  2293. [menuArray addObject:item];
  2294. }
  2295. if ([menuArray count] == 0)
  2296. return;
  2297. OptionalConfiguration options;
  2298. Color textColor, backgroundColor;
  2299. textColor.R = 0;
  2300. textColor.G = 0;
  2301. textColor.B = 0;
  2302. backgroundColor.R = 1;
  2303. backgroundColor.G = 1;
  2304. backgroundColor.B = 1;
  2305. NSInteger originY = 60;
  2306. options.arrowSize = 9;
  2307. options.marginXSpacing = 7;
  2308. options.marginYSpacing = 10;
  2309. options.intervalSpacing = 20;
  2310. options.menuCornerRadius = 6.5;
  2311. options.maskToBackground = NO;
  2312. options.shadowOfMenu = YES;
  2313. options.hasSeperatorLine = YES;
  2314. options.seperatorLineHasInsets = YES;
  2315. options.textColor = textColor;
  2316. options.menuBackgroundColor = backgroundColor;
  2317. CGRect rect = self.view.frame;
  2318. rect.origin.y = rect.origin.y + originY;
  2319. rect.size.height = rect.size.height - originY;
  2320. [CCMenu setTitleFont:[UIFont systemFontOfSize:12.0]];
  2321. [CCMenu showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2322. #endif
  2323. #if defined(MENU_BRAND) && defined(NO_MULTIUSER)
  2324. #endif
  2325. }
  2326. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2327. {
  2328. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2329. // STOP, erase all in queue networking
  2330. [app cancelAllOperations];
  2331. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2332. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2333. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2334. if (tableAccount)
  2335. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2336. // go to home sweet home
  2337. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2338. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2339. });
  2340. }
  2341. #pragma --------------------------------------------------------------------------------------------
  2342. #pragma mark ==== ReMenu ====
  2343. #pragma --------------------------------------------------------------------------------------------
  2344. - (void)createReMenuBackgroundView:(REMenu *)menu
  2345. {
  2346. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2347. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2348. [UIView animateWithDuration:0.2 animations:^{
  2349. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2350. if (height < self.tabBarController.tabBar.frame.size.height)
  2351. height = self.tabBarController.tabBar.frame.size.height;
  2352. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2353. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2354. }];
  2355. }
  2356. - (void)createReMainMenu
  2357. {
  2358. NSString *ordinamento;
  2359. NSString *groupBy = _directoryGroupBy;
  2360. __block NSString *nuovoOrdinamento;
  2361. NSString *titoloNuovo, *titoloAttuale;
  2362. BOOL ascendente;
  2363. __block BOOL nuovoAscendente;
  2364. UIImage *image;
  2365. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2366. if (app.selezionaItem == nil) app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)
  2367. subtitle:@""
  2368. image:[UIImage imageNamed:image_seleziona]
  2369. highlightedImage:nil
  2370. action:^(REMenuItem *item) {
  2371. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2372. [self tableViewSelect:YES];
  2373. }
  2374. }];
  2375. else app.selezionaItem = [app.selezionaItem initWithTitle:NSLocalizedString(@"_select_", nil)
  2376. subtitle:@""
  2377. image:[UIImage imageNamed:image_seleziona]
  2378. highlightedImage:nil
  2379. action:^(REMenuItem *item) {
  2380. if ([_sectionDataSource.allRecordsDataSource count] > 0)
  2381. [self tableViewSelect:YES];
  2382. }];
  2383. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2384. ordinamento = _directoryOrder;
  2385. if ([ordinamento isEqualToString:@"fileName"]) {
  2386. image = [UIImage imageNamed:image_MenuOrdeyByDate];
  2387. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2388. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2389. nuovoOrdinamento = @"fileDate";
  2390. }
  2391. if ([ordinamento isEqualToString:@"fileDate"]) {
  2392. image = [UIImage imageNamed:image_MenuOrderByFileName];
  2393. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2394. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2395. nuovoOrdinamento = @"fileName";
  2396. }
  2397. if (app.ordinaItem == nil) app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2398. subtitle:titoloAttuale
  2399. image:image
  2400. highlightedImage:nil
  2401. action:^(REMenuItem *item) {
  2402. [self orderTable:nuovoOrdinamento];
  2403. }];
  2404. else app.ordinaItem = [app.ordinaItem initWithTitle:titoloNuovo
  2405. subtitle:titoloAttuale
  2406. image:image
  2407. highlightedImage:nil
  2408. action:^(REMenuItem *item) {
  2409. [self orderTable:nuovoOrdinamento];
  2410. }];
  2411. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2412. ascendente = [CCUtility getAscendingSettings];
  2413. if (ascendente) {
  2414. image = [UIImage imageNamed:image_MenuOrdinamentoDiscendente];
  2415. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2416. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2417. nuovoAscendente = false;
  2418. }
  2419. if (!ascendente) {
  2420. image = [UIImage imageNamed:image_MenuOrdinamentoAscendente];
  2421. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2422. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2423. nuovoAscendente = true;
  2424. }
  2425. if (app.ascendenteItem == nil) app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2426. subtitle:titoloAttuale
  2427. image:image
  2428. highlightedImage:nil
  2429. action:^(REMenuItem *item) {
  2430. [self ascendingTable:nuovoAscendente];
  2431. }];
  2432. else app.ascendenteItem = [app.ascendenteItem initWithTitle:titoloNuovo
  2433. subtitle:titoloAttuale
  2434. image:image
  2435. highlightedImage:nil
  2436. action:^(REMenuItem *item) {
  2437. [self ascendingTable:nuovoAscendente];
  2438. }];
  2439. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2440. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2441. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2442. if (app.alphabeticItem == nil) app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2443. subtitle:@""
  2444. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2445. highlightedImage:nil
  2446. action:^(REMenuItem *item) {
  2447. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2448. else [self tableGroupBy:@"alphabetic"];
  2449. }];
  2450. else app.alphabeticItem = [app.alphabeticItem initWithTitle:titoloNuovo
  2451. subtitle:@""
  2452. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2453. highlightedImage:nil
  2454. action:^(REMenuItem *item) {
  2455. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2456. else [self tableGroupBy:@"alphabetic"];
  2457. }];
  2458. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2459. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2460. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2461. if (app.typefileItem == nil) app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2462. subtitle:@""
  2463. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2464. highlightedImage:nil
  2465. action:^(REMenuItem *item) {
  2466. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2467. else [self tableGroupBy:@"typefile"];
  2468. }];
  2469. else app.typefileItem = [app.typefileItem initWithTitle:titoloNuovo
  2470. subtitle:@""
  2471. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2472. highlightedImage:nil
  2473. action:^(REMenuItem *item) {
  2474. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2475. else [self tableGroupBy:@"typefile"];
  2476. }];
  2477. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2478. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2479. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2480. if (app.dateItem == nil) app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2481. subtitle:@""
  2482. image:[UIImage imageNamed:image_MenuGroupByDate]
  2483. highlightedImage:nil
  2484. action:^(REMenuItem *item) {
  2485. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2486. else [self tableGroupBy:@"date"];
  2487. }];
  2488. else app.dateItem = [app.dateItem initWithTitle:titoloNuovo
  2489. subtitle:@""
  2490. image:[UIImage imageNamed:image_MenuGroupByDate]
  2491. highlightedImage:nil
  2492. action:^(REMenuItem *item) {
  2493. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2494. else [self tableGroupBy:@"date"];
  2495. }];
  2496. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2497. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2498. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2499. if (app.directoryOnTopItem == nil) app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2500. subtitle:@""
  2501. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2502. highlightedImage:nil
  2503. action:^(REMenuItem *item) {
  2504. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2505. else [self directoryOnTop:YES];
  2506. }];
  2507. else app.directoryOnTopItem = [app.directoryOnTopItem initWithTitle:titoloNuovo
  2508. subtitle:@""
  2509. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2510. highlightedImage:nil
  2511. action:^(REMenuItem *item) {
  2512. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2513. else [self directoryOnTop:YES];
  2514. }];
  2515. // REMENU --------------------------------------------------------------------------------------------------------------
  2516. if (app.reMainMenu == nil) app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2517. else app.reMainMenu = [app.reMainMenu initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2518. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2519. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2520. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2521. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2522. app.reMainMenu.separatorHeight = 0.5;
  2523. app.reMainMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2524. app.reMainMenu.backgroundColor = COLOR_BACKGROUND_MENU;
  2525. app.reMainMenu.textColor = [UIColor blackColor];
  2526. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2527. app.reMainMenu.textShadowColor = nil;
  2528. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2529. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2530. app.reMainMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2531. app.reMainMenu.highlightedSeparatorColor = nil;
  2532. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2533. app.reMainMenu.highlightedTextShadowColor = nil;
  2534. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2535. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2536. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2537. app.reMainMenu.subtitleTextShadowColor = nil;
  2538. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2539. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2540. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2541. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2542. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2543. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2544. app.reMainMenu.borderWidth = 0.3;
  2545. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2546. app.reMainMenu.animationDuration = 0.2;
  2547. app.reMainMenu.closeAnimationDuration = 0.2;
  2548. app.reMainMenu.bounce = NO;
  2549. [app.reMainMenu setClosePreparationBlock:^{
  2550. // Backgroun reMenu (Gesture)
  2551. [_reMenuBackgroundView removeFromSuperview];
  2552. [app.controlCenter disableSingleFingerTap];
  2553. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2554. }];
  2555. }
  2556. - (void)toggleReMainMenu
  2557. {
  2558. if (app.reMainMenu.isOpen) {
  2559. [app.reMainMenu close];
  2560. } else {
  2561. [app.reMainMenu showFromNavigationController:self.navigationController];
  2562. // Backgroun reMenu & (Gesture)
  2563. [self createReMenuBackgroundView:app.reMainMenu];
  2564. [app.controlCenter enableSingleFingerTap:@selector(toggleReMainMenu) target:self];
  2565. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2566. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2567. }
  2568. }
  2569. - (void)createReSelectMenu
  2570. {
  2571. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2572. if (app.deleteItem == nil) app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2573. subtitle:@""
  2574. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2575. highlightedImage:nil
  2576. action:^(REMenuItem *item) {
  2577. [self deleteSelectionFile];
  2578. }];
  2579. else app.deleteItem = [app.deleteItem initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2580. subtitle:@""
  2581. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2582. highlightedImage:nil
  2583. action:^(REMenuItem *item) {
  2584. [self deleteSelectionFile];
  2585. }];
  2586. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2587. if (app.moveItem == nil) app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2588. subtitle:@""
  2589. image:[UIImage imageNamed:image_moveSelectedFiles]
  2590. highlightedImage:nil
  2591. action:^(REMenuItem *item) {
  2592. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2593. }];
  2594. else app.moveItem = [app.moveItem initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2595. subtitle:@""
  2596. image:[UIImage imageNamed:image_moveSelectedFiles]
  2597. highlightedImage:nil
  2598. action:^(REMenuItem *item) {
  2599. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2600. }];
  2601. if (app.isCryptoCloudMode) {
  2602. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2603. if (app.encryptItem == nil) app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2604. subtitle:@""
  2605. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2606. highlightedImage:nil
  2607. action:^(REMenuItem *item) {
  2608. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2609. }];
  2610. else app.encryptItem = [app.encryptItem initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2611. subtitle:@""
  2612. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2613. highlightedImage:nil
  2614. action:^(REMenuItem *item) {
  2615. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2616. }];
  2617. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2618. if (app.decryptItem == nil) app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2619. subtitle:@""
  2620. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2621. highlightedImage:nil
  2622. action:^(REMenuItem *item) {
  2623. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2624. }];
  2625. else app.decryptItem = [app.decryptItem initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2626. subtitle:@""
  2627. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2628. highlightedImage:nil
  2629. action:^(REMenuItem *item) {
  2630. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2631. }];
  2632. }
  2633. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2634. if (app.downloadItem == nil) app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2635. subtitle:@""
  2636. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2637. highlightedImage:nil
  2638. action:^(REMenuItem *item) {
  2639. [self downloadSelectedFiles];
  2640. }];
  2641. else app.downloadItem = [app.downloadItem initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2642. subtitle:@""
  2643. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2644. highlightedImage:nil
  2645. action:^(REMenuItem *item) {
  2646. [self downloadSelectedFiles];
  2647. }];
  2648. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2649. if (app.saveItem == nil) app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2650. subtitle:@""
  2651. image:[UIImage imageNamed:image_saveSelectedFiles]
  2652. highlightedImage:nil
  2653. action:^(REMenuItem *item) {
  2654. [self saveSelectedFiles];
  2655. }];
  2656. else app.saveItem = [app.saveItem initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2657. subtitle:@""
  2658. image:[UIImage imageNamed:image_saveSelectedFiles]
  2659. highlightedImage:nil
  2660. action:^(REMenuItem *item) {
  2661. [self saveSelectedFiles];
  2662. }];
  2663. // REMENU --------------------------------------------------------------------------------------------------------------
  2664. if (app.isCryptoCloudMode) {
  2665. if (app.reSelectMenu == nil)
  2666. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2667. else
  2668. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2669. } else {
  2670. if (app.reSelectMenu == nil)
  2671. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2672. else
  2673. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2674. }
  2675. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2676. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2677. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2678. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2679. app.reSelectMenu.separatorHeight = 0.5;
  2680. app.reSelectMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2681. app.reSelectMenu.backgroundColor = COLOR_BACKGROUND_MENU;
  2682. app.reSelectMenu.textColor = [UIColor blackColor];
  2683. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2684. app.reSelectMenu.textShadowColor = nil;
  2685. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2686. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2687. app.reSelectMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2688. app.reSelectMenu.highlightedSeparatorColor = nil;
  2689. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2690. app.reSelectMenu.highlightedTextShadowColor = nil;
  2691. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2692. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2693. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2694. app.reSelectMenu.subtitleTextShadowColor = nil;
  2695. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2696. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2697. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2698. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2699. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2700. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2701. app.reSelectMenu.borderWidth = 0.3;
  2702. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2703. app.reSelectMenu.closeAnimationDuration = 0.2;
  2704. app.reSelectMenu.animationDuration = 0.2;
  2705. app.reSelectMenu.bounce = NO;
  2706. [app.reSelectMenu setClosePreparationBlock:^{
  2707. // Backgroun reMenu (Gesture)
  2708. [_reMenuBackgroundView removeFromSuperview];
  2709. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2710. }];
  2711. }
  2712. - (void)toggleReSelectMenu
  2713. {
  2714. if (app.reSelectMenu.isOpen) {
  2715. [app.reSelectMenu close];
  2716. } else {
  2717. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2718. // Backgroun reMenu & (Gesture)
  2719. [self createReMenuBackgroundView:app.reSelectMenu];
  2720. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2721. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2722. }
  2723. }
  2724. #pragma --------------------------------------------------------------------------------------------
  2725. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2726. #pragma --------------------------------------------------------------------------------------------
  2727. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2728. {
  2729. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2730. UITableView *tableView = (UITableView*)self.view;
  2731. CGPoint touchPoint = [recognizer locationInView:self.view];
  2732. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2733. if (indexPath)
  2734. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2735. else
  2736. _metadata = nil;
  2737. [self becomeFirstResponder];
  2738. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2739. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2740. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2741. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2742. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2743. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2744. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2745. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2746. if (app.isCryptoCloudMode)
  2747. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2748. else
  2749. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2750. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2751. [menuController setMenuVisible:YES animated:YES];
  2752. }
  2753. }
  2754. - (BOOL)canBecomeFirstResponder
  2755. {
  2756. return YES;
  2757. }
  2758. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2759. {
  2760. // For copy file, copy files, Open in ... :
  2761. //
  2762. // NO Directory
  2763. // NO Error Passcode
  2764. // NO In Session mode (download/upload)
  2765. // NO Template
  2766. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2767. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2768. // NO Cryptated with Title lenght = 0
  2769. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2770. return YES;
  2771. }
  2772. return NO;
  2773. }
  2774. if (@selector(copyFiles:) == action) {
  2775. if (_isSelectedMode) {
  2776. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2777. for (CCMetadata *metadata in selectedMetadatas) {
  2778. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2779. // NO Cryptated with Title lenght = 0
  2780. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2781. return YES;
  2782. }
  2783. }
  2784. }
  2785. return NO;
  2786. }
  2787. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2788. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2789. NSArray *items = [pasteboard items];
  2790. if ([items count] == 1) {
  2791. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2792. NSDictionary *dic = [items objectAtIndex:0];
  2793. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2794. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2795. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2796. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2797. if (directoryUser) {
  2798. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2799. return YES;
  2800. }
  2801. return NO;
  2802. } else return NO;
  2803. }
  2804. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2805. BOOL isValid = NO;
  2806. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2807. NSArray *items = [pasteboard items];
  2808. if ([items count] <= 1) return NO;
  2809. for (NSDictionary *dic in items) {
  2810. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2811. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2812. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2813. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2814. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2815. if (directoryUser) {
  2816. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2817. isValid = YES;
  2818. }
  2819. }
  2820. return isValid;
  2821. }
  2822. return NO;
  2823. }
  2824. /************************************ COPY ************************************/
  2825. - (void)copyFile:(id)sender
  2826. {
  2827. // Remove all item
  2828. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2829. pasteboard.items = [[NSArray alloc] init];
  2830. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2831. [self copyFileToPasteboard:_metadata];
  2832. } else {
  2833. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2834. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2835. }
  2836. }
  2837. - (void)copyFiles:(id)sender
  2838. {
  2839. // Remove all item
  2840. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2841. pasteboard.items = [[NSArray alloc] init];
  2842. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2843. for (CCMetadata *metadata in selectedMetadatas) {
  2844. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2845. [self copyFileToPasteboard:metadata];
  2846. } else {
  2847. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2848. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2849. }
  2850. }
  2851. [self tableViewSelect:NO];
  2852. }
  2853. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2854. {
  2855. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2856. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2857. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2858. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], @"it.twsweb.Crypto-Cloud.CCMetadata",nil];
  2859. [items addObject:item];
  2860. [pasteboard setItems:items];
  2861. }
  2862. /************************************ OPEN IN ... ************************************/
  2863. - (void)openinFile:(id)sender
  2864. {
  2865. [self openIn:_metadata];
  2866. }
  2867. /************************************ PASTE ************************************/
  2868. - (void)pasteFile:(id)sender
  2869. {
  2870. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2871. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2872. }
  2873. - (void)pasteFileEncrypted:(id)sender
  2874. {
  2875. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2876. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2877. }
  2878. - (void)pasteFiles:(id)sender
  2879. {
  2880. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2881. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2882. }
  2883. - (void)pasteFilesEncrypted:(id)sender
  2884. {
  2885. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2886. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2887. }
  2888. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2889. {
  2890. for (NSDictionary *dic in items) {
  2891. // key : it.twsweb.Crypto-Cloud.CCMetadata
  2892. // Value : (NSData) metadata
  2893. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2894. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2895. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2896. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2897. if (directoryUser) {
  2898. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2899. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2900. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2901. }
  2902. }
  2903. }
  2904. }
  2905. #pragma --------------------------------------------------------------------------------------------
  2906. #pragma mark ===== Lock Passcode =====
  2907. #pragma --------------------------------------------------------------------------------------------
  2908. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2909. {
  2910. return _failedAttempts;
  2911. }
  2912. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2913. {
  2914. return _lockUntilDate;
  2915. }
  2916. - (void)passcodeViewCloseButtonPressed:(id)sender
  2917. {
  2918. [self dismissViewControllerAnimated:YES completion:nil];
  2919. }
  2920. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2921. {
  2922. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2923. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2924. _lockUntilDate = nil;
  2925. _failedAttempts = 0;
  2926. aResultHandler(YES);
  2927. } else aResultHandler(NO);
  2928. } else aResultHandler(YES);
  2929. }
  2930. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2931. {
  2932. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2933. switch (aViewController.type) {
  2934. case BKPasscodeViewControllerCheckPasscodeType: {
  2935. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2936. CCCrypto *crypto = [[CCCrypto alloc] init];
  2937. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2938. if ([crypto verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2939. // scriviamo il passcode
  2940. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2941. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2942. } else {
  2943. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2944. [alertView show];
  2945. }
  2946. }
  2947. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2948. // possiamo procedere alla prossima directory
  2949. [self performSegueDirectoryWithControlPasscode:false];
  2950. // avviamo la sessione Passcode Lock con now
  2951. app.sessionePasscodeLock = [NSDate date];
  2952. }
  2953. // disattivazione lock cartella
  2954. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2955. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2956. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2957. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2958. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2959. }
  2960. [self.tableView reloadData];
  2961. }
  2962. }
  2963. break;
  2964. default:
  2965. break;
  2966. }
  2967. }
  2968. - (void)comandoLockPassword
  2969. {
  2970. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2971. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2972. // se non è abilitato il Lock Passcode esci
  2973. if ([[CCUtility getBlockCode] length] == 0) {
  2974. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2975. [alertView show];
  2976. return;
  2977. }
  2978. // se è richiesta la disattivazione si chiede la password
  2979. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2980. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2981. viewController.delegate = self;
  2982. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2983. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2984. viewController.inputViewTitlePassword = YES;
  2985. if ([CCUtility getSimplyBlockCode]) {
  2986. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2987. viewController.passcodeInputView.maximumLength = 6;
  2988. } else {
  2989. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2990. viewController.passcodeInputView.maximumLength = 64;
  2991. }
  2992. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  2993. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2994. viewController.touchIDManager = touchIDManager;
  2995. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2996. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2997. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_CRYPTOCLOUD;
  2998. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2999. [self presentViewController:navigationController animated:YES completion:nil];
  3000. return;
  3001. }
  3002. // ---------------- ACTIVATE PASSWORD
  3003. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  3004. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3005. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3006. } else {
  3007. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  3008. }
  3009. }
  3010. #pragma mark -
  3011. #pragma --------------------------------------------------------------------------------------------
  3012. #pragma mark ===== Swipe Tablet -> menu =====
  3013. #pragma --------------------------------------------------------------------------------------------
  3014. // more
  3015. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  3016. return NSLocalizedString(@"_more_", nil);
  3017. }
  3018. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  3019. {
  3020. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3021. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3022. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  3023. BOOL offlineFolder = NO;
  3024. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3025. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3026. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3027. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3028. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3029. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  3030. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3031. offlineFolder = YES;
  3032. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3033. if (_metadata.favorite) {
  3034. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3035. } else {
  3036. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3037. }
  3038. if (_metadata.directory) {
  3039. // calcolo lockServerUrl
  3040. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3041. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3042. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3043. }
  3044. /******************************************* AHKActionSheet *******************************************/
  3045. UIImage *iconHeader;
  3046. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3047. actionSheet.animationDuration = 0.2;
  3048. actionSheet.blurRadius = 0.0f;
  3049. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3050. actionSheet.buttonHeight = 50.0;
  3051. actionSheet.cancelButtonHeight = 50.0f;
  3052. actionSheet.separatorHeight = 5.0f;
  3053. actionSheet.automaticallyTintButtonImages = @(NO);
  3054. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_CRYPTOCLOUD };
  3055. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_TEXT_ANTHRACITE };
  3056. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:COLOR_BRAND };
  3057. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:COLOR_TEXT_ANTHRACITE };
  3058. actionSheet.separatorColor = COLOR_SEPARATOR_TABLE;
  3059. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3060. /******************************************* DIRECTORY *******************************************/
  3061. if (_metadata.directory) {
  3062. UIImage *iconHeader;
  3063. BOOL lockDirectory = NO;
  3064. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3065. // Directory bloccata ?
  3066. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3067. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3068. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3069. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3070. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3071. image: iconHeader
  3072. backgroundColor: COLOR_TABBAR
  3073. height: 50.0
  3074. type: AHKActionSheetButtonTypeDisabled
  3075. handler: nil
  3076. ];
  3077. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3078. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3079. image:[UIImage imageNamed:image_actionSheetRename]
  3080. backgroundColor:[UIColor whiteColor]
  3081. height: 50.0
  3082. type:AHKActionSheetButtonTypeDefault
  3083. handler:^(AHKActionSheet *as) {
  3084. // close swipe
  3085. [self setEditing:NO animated:YES];
  3086. //chiediamo il nome del file
  3087. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3088. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3089. alertView.tag = alertRename;
  3090. UITextField *textField = [alertView textFieldAtIndex:0];
  3091. textField.text = _metadata.fileNamePrint;
  3092. [alertView show];
  3093. }];
  3094. }
  3095. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3096. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3097. image:[UIImage imageNamed:image_actionSheetMove]
  3098. backgroundColor:[UIColor whiteColor]
  3099. height: 50.0
  3100. type:AHKActionSheetButtonTypeDefault
  3101. handler:^(AHKActionSheet *as) {
  3102. // close swipe
  3103. [self setEditing:NO animated:YES];
  3104. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3105. }];
  3106. }
  3107. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3108. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3109. image:[UIImage imageNamed:image_actionSheetCrypto]
  3110. backgroundColor:[UIColor whiteColor]
  3111. height: 50.0
  3112. type:AHKActionSheetButtonTypeEncrypted
  3113. handler:^(AHKActionSheet *as) {
  3114. // close swipe
  3115. [self setEditing:NO animated:YES];
  3116. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3117. }];
  3118. }
  3119. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3120. [actionSheet addButtonWithTitle:titoloLock
  3121. image:[UIImage imageNamed:image_actionSheetLock]
  3122. backgroundColor:[UIColor whiteColor]
  3123. height: 50.0
  3124. type:AHKActionSheetButtonTypeEncrypted
  3125. handler:^(AHKActionSheet *as) {
  3126. // close swipe
  3127. [self setEditing:NO animated:YES];
  3128. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3129. }];
  3130. }
  3131. if (_metadata.cryptated == NO && app.hasServerShareSupport && !lockDirectory) {
  3132. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3133. image:[UIImage imageNamed:image_actionSheetShare]
  3134. backgroundColor:[UIColor whiteColor]
  3135. height: 50.0
  3136. type:AHKActionSheetButtonTypeDefault
  3137. handler:^(AHKActionSheet *as) {
  3138. // close swipe
  3139. [self setEditing:NO animated:YES];
  3140. [self openWindowShare:_metadata];
  3141. }];
  3142. }
  3143. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3144. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3145. image:[UIImage imageNamed:image_folderphotocamera]
  3146. backgroundColor:[UIColor whiteColor]
  3147. height: 50.0
  3148. type:AHKActionSheetButtonTypeDefault
  3149. handler:^(AHKActionSheet *as) {
  3150. // close swipe
  3151. [self setEditing:NO animated:YES];
  3152. // Settings new folder Automatatic upload
  3153. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3154. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3155. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3156. [CCCoreData clearDateReadDirectory:oldPath activeAccount:app.activeAccount];
  3157. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3158. [app.activePhotosCameraUpload reloadDatasourceForced];
  3159. [self readFolderWithForced:YES serverUrl:serverUrl];
  3160. NSLog(@"[LOG] Update Folder Photo");
  3161. NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3162. if ([folderCameraUpload length] > 0)
  3163. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolderRefresh];
  3164. }];
  3165. }
  3166. #ifndef NO_OFFLINE
  3167. NSString *upDir = [CCUtility deletingLastPathComponentFromServerUrl:dirServerUrl];
  3168. NSString *homeDir = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  3169. if (!lockDirectory && ([upDir isEqualToString:homeDir] || ![CCCoreData isOfflineDirectoryServerUrl:upDir activeAccount:app.activeAccount]) && !_metadata.cryptated) {
  3170. [actionSheet addButtonWithTitle:titleOfflineFolder
  3171. image:[UIImage imageNamed:image_actionSheetOffline]
  3172. backgroundColor:[UIColor whiteColor]
  3173. height: 50.0
  3174. type:AHKActionSheetButtonTypeDefault
  3175. handler:^(AHKActionSheet *as) {
  3176. // close swipe
  3177. [self setEditing:NO animated:YES];
  3178. if (offlineFolder == NO) {
  3179. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"",nil) message:NSLocalizedString(@"_offline_folder_confirm_",nil) delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3180. alertView.tag = alertOfflineFolder;
  3181. [alertView show];
  3182. } else {
  3183. // remove tag offline for all folder/subfolder/file
  3184. NSArray *directories = [CCCoreData getOfflineDirectoryActiveAccount:app.activeAccount];
  3185. for (TableDirectory *directory in directories)
  3186. if ([directory.serverUrl containsString:dirServerUrl]) {
  3187. [CCCoreData setOfflineDirectoryServerUrl:directory.serverUrl offline:NO activeAccount:app.activeAccount];
  3188. [CCCoreData removeOfflineAllFileFromServerUrl:directory.serverUrl activeAccount:app.activeAccount];
  3189. }
  3190. [self performSelector:@selector(reloadDatasource) withObject:nil];
  3191. }
  3192. }];
  3193. }
  3194. #endif
  3195. if (!lockDirectory && !_metadata.cryptated) {
  3196. [actionSheet addButtonWithTitle:titleFavorite
  3197. image:[UIImage imageNamed:image_actionSheetFavorite]
  3198. backgroundColor:[UIColor whiteColor]
  3199. height: 50.0
  3200. type:AHKActionSheetButtonTypeDefault
  3201. handler:^(AHKActionSheet *as) {
  3202. // close swipe
  3203. [self setEditing:NO animated:YES];
  3204. if (_metadata.favorite)
  3205. [self removeFavorite:_metadata];
  3206. else
  3207. [self addFavorite:_metadata];
  3208. }];
  3209. }
  3210. [actionSheet show];
  3211. }
  3212. /******************************************* FILE *******************************************/
  3213. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3214. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3215. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3216. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3217. else
  3218. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3219. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3220. image: iconHeader
  3221. backgroundColor: COLOR_TABBAR
  3222. height: 50.0
  3223. type: AHKActionSheetButtonTypeDisabled
  3224. handler: nil
  3225. ];
  3226. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3227. image:[UIImage imageNamed:image_actionSheetRename]
  3228. backgroundColor:[UIColor whiteColor]
  3229. height: 50.0
  3230. type:AHKActionSheetButtonTypeDefault
  3231. handler:^(AHKActionSheet *as) {
  3232. // close swipe
  3233. [self setEditing:NO animated:YES];
  3234. //chiediamo il nome del file
  3235. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3236. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3237. alertView.tag = alertRename;
  3238. UITextField *textField = [alertView textFieldAtIndex:0];
  3239. textField.text = _metadata.fileNamePrint;
  3240. [alertView show];
  3241. }];
  3242. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3243. image:[UIImage imageNamed:image_actionSheetMove]
  3244. backgroundColor:[UIColor whiteColor]
  3245. height: 50.0
  3246. type:AHKActionSheetButtonTypeDefault
  3247. handler:^(AHKActionSheet *as) {
  3248. // close swipe
  3249. [self setEditing:NO animated:YES];
  3250. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3251. }];
  3252. [actionSheet addButtonWithTitle:NSLocalizedString(@"_reload_", nil)
  3253. image:[UIImage imageNamed:image_actionSheetReload]
  3254. backgroundColor:[UIColor whiteColor]
  3255. height: 50.0
  3256. type:AHKActionSheetButtonTypeDefault
  3257. handler:^(AHKActionSheet *as) {
  3258. // close swipe
  3259. [self setEditing:NO animated:YES];
  3260. [self performSelector:@selector(reloadFile:) withObject:_metadata];
  3261. }];
  3262. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3263. image:[UIImage imageNamed:image_actionSheetOpenIn]
  3264. backgroundColor:[UIColor whiteColor]
  3265. height: 50.0
  3266. type:AHKActionSheetButtonTypeDefault
  3267. handler:^(AHKActionSheet *as) {
  3268. // close swipe
  3269. [self setEditing:NO animated:YES];
  3270. [self performSelector:@selector(openIn:) withObject:_metadata];
  3271. }];
  3272. if (_metadata.cryptated == NO && app.hasServerShareSupport) {
  3273. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3274. image:[UIImage imageNamed:image_actionSheetShare]
  3275. backgroundColor:[UIColor whiteColor]
  3276. height: 50.0
  3277. type:AHKActionSheetButtonTypeDefault
  3278. handler:^(AHKActionSheet *as) {
  3279. // close swipe
  3280. [self setEditing:NO animated:YES];
  3281. [self openWindowShare:_metadata];
  3282. }];
  3283. }
  3284. if (app.isCryptoCloudMode) {
  3285. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3286. image:[UIImage imageNamed:image_actionSheetCrypto]
  3287. backgroundColor:[UIColor whiteColor]
  3288. height: 50.0
  3289. type:AHKActionSheetButtonTypeEncrypted
  3290. handler:^(AHKActionSheet *as) {
  3291. // close swipe
  3292. [self setEditing:NO animated:YES];
  3293. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3294. }];
  3295. }
  3296. #ifndef NO_OFFLINE
  3297. if (!_metadata.cryptated) {
  3298. [actionSheet addButtonWithTitle:titoloOffline
  3299. image:[UIImage imageNamed:image_actionSheetOffline]
  3300. backgroundColor:[UIColor whiteColor]
  3301. height: 50.0
  3302. type:AHKActionSheetButtonTypeDefault
  3303. handler:^(AHKActionSheet *as) {
  3304. // close swipe
  3305. [self setEditing:NO animated:YES];
  3306. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) {
  3307. [self removeOffline:_metadata];
  3308. } else {
  3309. [self addOffline:_metadata];
  3310. }
  3311. }];
  3312. }
  3313. #endif
  3314. if (!_metadata.cryptated) {
  3315. [actionSheet addButtonWithTitle:titleFavorite
  3316. image:[UIImage imageNamed:image_actionSheetFavorite]
  3317. backgroundColor:[UIColor whiteColor]
  3318. height: 50.0
  3319. type:AHKActionSheetButtonTypeDefault
  3320. handler:^(AHKActionSheet *as) {
  3321. // close swipe
  3322. [self setEditing:NO animated:YES];
  3323. if (_metadata.favorite)
  3324. [self removeFavorite:_metadata];
  3325. else
  3326. [self addFavorite:_metadata];
  3327. }];
  3328. }
  3329. [actionSheet addButtonWithTitle:NSLocalizedString(@"_add_local_", nil)
  3330. image:[UIImage imageNamed:image_actionSheetLocal]
  3331. backgroundColor:[UIColor whiteColor]
  3332. height: 50.0
  3333. type:AHKActionSheetButtonTypeDefault
  3334. handler:^(AHKActionSheet *as) {
  3335. // close swipe
  3336. [self setEditing:NO animated:YES];
  3337. [self performSelector:@selector(addLocal:) withObject:_metadata];
  3338. }];
  3339. [actionSheet show];
  3340. }
  3341. /******************************************* TEMPLATE *******************************************/
  3342. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3343. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3344. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3345. image: iconHeader
  3346. backgroundColor: COLOR_TABBAR
  3347. height: 50.0
  3348. type: AHKActionSheetButtonTypeDisabled
  3349. handler: nil
  3350. ];
  3351. if ([_metadata.model isEqualToString:@"note"]) {
  3352. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3353. image:[UIImage imageNamed:image_actionSheetRename]
  3354. backgroundColor:[UIColor whiteColor]
  3355. height: 50.0
  3356. type:AHKActionSheetButtonTypeDefault
  3357. handler:^(AHKActionSheet *as) {
  3358. // close swipe
  3359. [self setEditing:NO animated:YES];
  3360. //chiediamo il nome del file
  3361. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3362. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3363. alertView.tag = alertRename;
  3364. UITextField *textField = [alertView textFieldAtIndex:0];
  3365. textField.text = _metadata.fileNamePrint;
  3366. [alertView show];
  3367. }];
  3368. }
  3369. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3370. image:[UIImage imageNamed:image_actionSheetMove]
  3371. backgroundColor:[UIColor whiteColor]
  3372. height: 50.0
  3373. type:AHKActionSheetButtonTypeDefault
  3374. handler:^(AHKActionSheet *as) {
  3375. // close swipe
  3376. [self setEditing:NO animated:YES];
  3377. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3378. }];
  3379. [actionSheet show];
  3380. }
  3381. }
  3382. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3383. {
  3384. return NSLocalizedString(@"_delete_", nil);
  3385. }
  3386. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3387. {
  3388. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3389. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3390. else return YES;
  3391. }
  3392. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3393. {
  3394. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3395. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3396. else return UITableViewCellEditingStyleDelete;
  3397. }
  3398. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3399. {
  3400. BOOL lockDirectory = NO;
  3401. // Directory locked ?
  3402. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addFileName:_metadata.fileNameData];
  3403. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3404. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3405. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  3406. return;
  3407. }
  3408. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3409. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3410. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3411. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3412. style:UIAlertActionStyleDestructive
  3413. handler:^(UIAlertAction *action) {
  3414. [self performSelector:@selector(deleteFile) withObject:nil];
  3415. }]];
  3416. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3417. style:UIAlertActionStyleCancel
  3418. handler:^(UIAlertAction *action) {
  3419. [alertController dismissViewControllerAnimated:YES completion:nil];
  3420. }]];
  3421. alertController.popoverPresentationController.sourceView = self.view;
  3422. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3423. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3424. [alertController.view layoutIfNeeded];
  3425. [self presentViewController:alertController animated:YES completion:nil];
  3426. }
  3427. }
  3428. #pragma --------------------------------------------------------------------------------------------
  3429. #pragma mark - ==== Datasource ====
  3430. #pragma --------------------------------------------------------------------------------------------
  3431. - (void)clearDateReadDataSource:(NSNotification *)notification
  3432. {
  3433. _dateReadDataSource = Nil;
  3434. [self reloadDatasource];
  3435. }
  3436. - (void)reloadDatasource
  3437. {
  3438. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3439. }
  3440. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3441. {
  3442. // test
  3443. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3444. return;
  3445. // Search Mode
  3446. if(_isSearchMode) {
  3447. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3448. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3449. } else {
  3450. [self readFolderWithForced:NO serverUrl:serverUrl];
  3451. }
  3452. [self tableViewReload];
  3453. [self setTitleBackgroundTableView:nil];
  3454. [app updateApplicationIconBadgeNumber];
  3455. return;
  3456. }
  3457. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3458. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3459. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3460. [app.controlCenterTransfer reloadDatasource];
  3461. } else {
  3462. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3463. if (main) {
  3464. [main reloadDatasource];
  3465. } else {
  3466. [self tableViewReload];
  3467. [app.controlCenterTransfer reloadDatasource];
  3468. }
  3469. }
  3470. return;
  3471. }
  3472. // Offline folder ?
  3473. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3474. [app.controlCenterTransfer reloadDatasource];
  3475. // Settaggio variabili per le ottimizzazioni
  3476. _directoryGroupBy = [CCUtility getGroupBySettings];
  3477. _directoryOrder = [CCUtility getOrderSettings];
  3478. // Controllo data lettura Data Source
  3479. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3480. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3481. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3482. _dateReadDataSource = [NSDate date];
  3483. // Data Source
  3484. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3485. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3486. } else {
  3487. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3488. }
  3489. [self tableViewReload];
  3490. [self setTitleBackgroundTableView];
  3491. [app updateApplicationIconBadgeNumber];
  3492. }
  3493. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3494. {
  3495. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3496. if (selectedRows.count > 0) {
  3497. for (NSIndexPath *selectionIndex in selectedRows) {
  3498. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3499. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3500. [metadatas addObject:metadata];
  3501. }
  3502. }
  3503. return metadatas;
  3504. }
  3505. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3506. {
  3507. NSInteger section = indexPath.section + 1;
  3508. NSInteger row = indexPath.row + 1;
  3509. NSInteger totSections =[_sectionDataSource.sections count] ;
  3510. if ((totSections < section) || (section > totSections)) {
  3511. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3512. return nil;
  3513. }
  3514. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3515. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3516. if (fileIDs) {
  3517. NSInteger totRows =[fileIDs count] ;
  3518. if ((totRows < row) || (row > totRows)) {
  3519. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3520. return nil;
  3521. }
  3522. } else {
  3523. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3524. return nil;
  3525. }
  3526. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3527. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3528. }
  3529. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3530. {
  3531. NSInteger totSections =[_sectionDataSource.sections count] ;
  3532. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3533. #if DEBUG
  3534. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3535. [alertView show];
  3536. #endif
  3537. return nil;
  3538. }
  3539. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3540. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3541. }
  3542. #pragma --------------------------------------------------------------------------------------------
  3543. #pragma mark - ==== Table ====
  3544. #pragma --------------------------------------------------------------------------------------------
  3545. - (void)tableViewSelect:(BOOL)edit
  3546. {
  3547. // chiudiamo eventuali swipe aperti
  3548. if (edit) [self.tableView setEditing:NO animated:NO];
  3549. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3550. [self.tableView setEditing:edit animated:YES];
  3551. _isSelectedMode = edit;
  3552. if (edit)
  3553. [self setUINavigationBarSelected];
  3554. else
  3555. [self setUINavigationBarDefault];
  3556. [self setTitle];
  3557. }
  3558. - (void)tableViewReload
  3559. {
  3560. // ricordiamoci le row selezionate
  3561. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3562. [self.tableView reloadData];
  3563. for (NSIndexPath *path in indexPaths)
  3564. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3565. [self setTableViewFooter];
  3566. if (self.tableView.editing)
  3567. [self setTitle];
  3568. }
  3569. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3570. {
  3571. return 60;
  3572. }
  3573. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3574. {
  3575. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3576. }
  3577. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3578. {
  3579. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3580. }
  3581. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3582. {
  3583. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3584. NSString *sectionTitle = [sections objectAtIndex:section];
  3585. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3586. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3587. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3588. return 20.f;
  3589. }
  3590. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3591. {
  3592. float shift;
  3593. UIVisualEffectView *visualEffectView;
  3594. // Titolo
  3595. NSString *titleSection;
  3596. // Controllo
  3597. if ([_sectionDataSource.sections count] == 0)
  3598. return nil;
  3599. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3600. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3601. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3602. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3603. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3604. else titleSection = NSLocalizedString(titleSection,nil);
  3605. // Formato titolo
  3606. NSString *currentDevice = [CCUtility currentDevice];
  3607. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3608. visualEffectView = [[UIVisualEffectView alloc] init];
  3609. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  3610. } else {
  3611. UIVisualEffect *blurEffect;
  3612. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3613. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3614. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR;
  3615. }
  3616. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3617. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3618. else shift = - 20;
  3619. } else shift = - 10;
  3620. // Title
  3621. UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3622. titleLabel.backgroundColor=[UIColor clearColor];
  3623. titleLabel.textColor = COLOR_TEXT_ANTHRACITE;
  3624. titleLabel.font = [UIFont systemFontOfSize:12];
  3625. titleLabel.textAlignment = NSTextAlignmentLeft;
  3626. titleLabel.text = titleSection;
  3627. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3628. [visualEffectView addSubview:titleLabel];
  3629. // Elements
  3630. UILabel *elementLabel=[[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3631. elementLabel.backgroundColor=[UIColor clearColor];
  3632. elementLabel.textColor = COLOR_TEXT_ANTHRACITE;
  3633. elementLabel.font = [UIFont systemFontOfSize:12];
  3634. elementLabel.textAlignment = NSTextAlignmentRight;
  3635. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3636. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3637. NSUInteger rowsCount = [metadatas count];
  3638. if (rowsCount == 0) return nil;
  3639. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3640. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3641. [visualEffectView addSubview:elementLabel];
  3642. return visualEffectView;
  3643. }
  3644. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3645. {
  3646. return [_sectionDataSource.sections indexOfObject:title];
  3647. }
  3648. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3649. {
  3650. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3651. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3652. else
  3653. return nil;
  3654. }
  3655. /*
  3656. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3657. {
  3658. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3659. }
  3660. }
  3661. */
  3662. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3663. {
  3664. NSString *typeCell;
  3665. NSString *dataFile;
  3666. NSString *lunghezzaFile;
  3667. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3668. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3669. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3670. else typeCell = @"CellMainTransfer";
  3671. if (!metadata)
  3672. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3673. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3674. // separator
  3675. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3676. // change color selection
  3677. UIView *selectionColor = [[UIView alloc] init];
  3678. selectionColor.backgroundColor = COLOR_SELECT_BACKGROUND;
  3679. cell.selectedBackgroundView = selectionColor;
  3680. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3681. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = COLOR_TRANSFER_BACKGROUND;
  3682. // ----------------------------------------------------------------------------------------------------------
  3683. // DEFAULT
  3684. // ----------------------------------------------------------------------------------------------------------
  3685. cell.fileImageView.image = nil;
  3686. cell.statusImageView.image = nil;
  3687. cell.offlineImageView.image = nil;
  3688. cell.synchronizedImageView.image = nil;
  3689. cell.sharedImageView.image = nil;
  3690. cell.labelTitle.enabled = YES;
  3691. cell.labelTitle.text = @"";
  3692. cell.labelInfoFile.enabled = YES;
  3693. cell.labelInfoFile.text = @"";
  3694. cell.progressView.progress = 0.0;
  3695. cell.progressView.hidden = YES;
  3696. cell.cancelTaskButton.hidden = YES;
  3697. cell.reloadTaskButton.hidden = YES;
  3698. cell.stopTaskButton.hidden = YES;
  3699. // colori e font
  3700. if (metadata.cryptated) {
  3701. cell.labelTitle.textColor = COLOR_CRYPTOCLOUD;
  3702. cell.labelInfoFile.textColor = [UIColor blackColor];
  3703. } else {
  3704. cell.labelTitle.textColor = COLOR_TEXT_ANTHRACITE;
  3705. cell.labelInfoFile.textColor = [UIColor blackColor];
  3706. }
  3707. // ----------------------------------------------------------------------------------------------------------
  3708. // File Name & Folder
  3709. // ----------------------------------------------------------------------------------------------------------
  3710. // nome del file
  3711. cell.labelTitle.text = metadata.fileNamePrint;
  3712. // è una directory
  3713. if (metadata.directory) {
  3714. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3715. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3716. lunghezzaFile = @" ";
  3717. // ----------------------------------------------------------------------------------------------------------
  3718. // Offline Folder
  3719. // ----------------------------------------------------------------------------------------------------------
  3720. NSString *directoryServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3721. BOOL isOfflineDirectory = [CCCoreData isOfflineDirectoryServerUrl:directoryServerUrl activeAccount:app.activeAccount];
  3722. // Verify Offline
  3723. if (_isOfflineServerUrl == YES && isOfflineDirectory == NO) {
  3724. [CCCoreData setOfflineDirectoryServerUrl:directoryServerUrl offline:YES activeAccount:app.activeAccount];
  3725. isOfflineDirectory = YES;
  3726. }
  3727. if (isOfflineDirectory) {
  3728. cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3729. }
  3730. // ----------------------------------------------------------------------------------------------------------
  3731. // Favorite Folder
  3732. // ----------------------------------------------------------------------------------------------------------
  3733. if (metadata.favorite) {
  3734. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3735. }
  3736. // Animation synchronized gif
  3737. if ([[CCSynchronize sharedSynchronize] synchronizeFolderAnimationDirectory:[[NSArray alloc] initWithObjects:directoryServerUrl, nil] setGraphicsFolder:NO]) {
  3738. NSURL *myURL;
  3739. if (metadata.cryptated) myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3740. else myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3741. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  3742. }
  3743. } else {
  3744. // è un file
  3745. dataFile = [CCUtility dateDiff:metadata.date];
  3746. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3747. // Plist ancora da scaricare
  3748. if (metadata.cryptated && [metadata.title length] == 0) {
  3749. dataFile = @" ";
  3750. lunghezzaFile = @" ";
  3751. }
  3752. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3753. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3754. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3755. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3756. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3757. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3758. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3759. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3760. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3761. else
  3762. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3763. }
  3764. // Plist ancora da scaricare
  3765. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3766. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3767. cell.accessoryType = UITableViewCellAccessoryNone;
  3768. }
  3769. // ----------------------------------------------------------------------------------------------------------
  3770. // File Image View
  3771. // ----------------------------------------------------------------------------------------------------------
  3772. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3773. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3774. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3775. if (cell.fileImageView.image == nil) {
  3776. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3777. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3778. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3779. dispatch_async(dispatch_get_main_queue(), ^{
  3780. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3781. if (cell)
  3782. cell.fileImageView.image = image;
  3783. });
  3784. });
  3785. }
  3786. } else {
  3787. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3788. if (metadata.thumbnailExists)
  3789. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3790. }
  3791. // ----------------------------------------------------------------------------------------------------------
  3792. // Image Status cyptated & Lock Passcode
  3793. // ----------------------------------------------------------------------------------------------------------
  3794. // File Cyptated
  3795. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3796. cell.statusImageView.image = [UIImage imageNamed:image_lock];
  3797. }
  3798. // Directory con passcode lock attivato
  3799. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3800. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length])) cell.statusImageView.image = [UIImage imageNamed:image_passcode];
  3801. // ----------------------------------------------------------------------------------------------------------
  3802. // Offline
  3803. // ----------------------------------------------------------------------------------------------------------
  3804. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3805. if (isOfflineFile) {
  3806. cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3807. }
  3808. // ----------------------------------------------------------------------------------------------------------
  3809. // Favorite
  3810. // ----------------------------------------------------------------------------------------------------------
  3811. if (metadata.favorite) {
  3812. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3813. }
  3814. // ----------------------------------------------------------------------------------------------------------
  3815. // Share
  3816. // ----------------------------------------------------------------------------------------------------------
  3817. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3818. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3819. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3820. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3821. // Aggiungiamo il Tap per le shared
  3822. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3823. if (isShare) {
  3824. cell.sharedImageView.image = [UIImage imageNamed:image_shareConnect];
  3825. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3826. [tap setNumberOfTapsRequired:1];
  3827. cell.sharedImageView.userInteractionEnabled = YES;
  3828. [cell.sharedImageView addGestureRecognizer:tap];
  3829. }
  3830. if (isMounted) {
  3831. cell.sharedImageView.image = [UIImage imageNamed:image_shareMounted];
  3832. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3833. [tap setNumberOfTapsRequired:1];
  3834. cell.sharedImageView.userInteractionEnabled = YES;
  3835. [cell.sharedImageView addGestureRecognizer:tap];
  3836. }
  3837. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3838. if ([shareLink length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareLink];
  3839. if ([shareUserAndGroup length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareUser];
  3840. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3841. [tap setNumberOfTapsRequired:1];
  3842. cell.sharedImageView.userInteractionEnabled = YES;
  3843. [cell.sharedImageView addGestureRecognizer:tap];
  3844. }
  3845. } else {
  3846. cell.sharedImageView.userInteractionEnabled = NO;
  3847. }
  3848. // ----------------------------------------------------------------------------------------------------------
  3849. // downloadFile
  3850. // ----------------------------------------------------------------------------------------------------------
  3851. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3852. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusdownloadcrypto];
  3853. else cell.statusImageView.image = [UIImage imageNamed:image_statusdownload];
  3854. // sessionTaskIdentifier : RELOAD + STOP
  3855. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3856. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3857. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3858. cell.cancelTaskButton.hidden = NO;
  3859. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3860. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3861. cell.reloadTaskButton.hidden = NO;
  3862. }
  3863. // sessionTaskIdentifierPlist : RELOAD
  3864. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3865. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3866. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3867. cell.reloadTaskButton.hidden = NO;
  3868. }
  3869. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3870. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3871. if (progress > 0) {
  3872. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_CRYPTOCLOUD;
  3873. else cell.progressView.progressTintColor = COLOR_TEXT_ANTHRACITE;
  3874. cell.progressView.progress = progress;
  3875. cell.progressView.hidden = NO;
  3876. }
  3877. // ----------------------------------------------------------------------------------------------------------
  3878. // downloadFile Error
  3879. // ----------------------------------------------------------------------------------------------------------
  3880. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3881. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3882. if ([metadata.sessionError length] == 0)
  3883. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3884. else
  3885. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3886. }
  3887. }
  3888. // ----------------------------------------------------------------------------------------------------------
  3889. // uploadFile
  3890. // ----------------------------------------------------------------------------------------------------------
  3891. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3892. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusuploadcrypto];
  3893. else cell.statusImageView.image = [UIImage imageNamed:image_statusupload];
  3894. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetaskcrypto] forState:UIControlStateNormal];
  3895. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetask] forState:UIControlStateNormal];
  3896. cell.cancelTaskButton.hidden = NO;
  3897. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3898. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3899. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3900. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusstopcrypto];
  3901. else cell.statusImageView.image = [UIImage imageNamed:image_statusstop];
  3902. cell.reloadTaskButton.hidden = NO;
  3903. cell.stopTaskButton.hidden = YES;
  3904. } else {
  3905. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3906. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3907. cell.stopTaskButton.hidden = NO;
  3908. cell.reloadTaskButton.hidden = YES;
  3909. }
  3910. // se non c'è una preview in bianconero metti l'immagine di default
  3911. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3912. cell.fileImageView.image = [UIImage imageNamed:image_uploaddisable];
  3913. cell.labelTitle.enabled = NO;
  3914. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3915. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3916. if (progress > 0) {
  3917. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_CRYPTOCLOUD;
  3918. else cell.progressView.progressTintColor = COLOR_TEXT_ANTHRACITE;
  3919. cell.progressView.progress = progress;
  3920. cell.progressView.hidden = NO;
  3921. }
  3922. // ----------------------------------------------------------------------------------------------------------
  3923. // uploadFileError
  3924. // ----------------------------------------------------------------------------------------------------------
  3925. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3926. cell.labelTitle.enabled = NO;
  3927. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3928. if ([metadata.sessionError length] == 0)
  3929. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3930. else
  3931. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3932. }
  3933. }
  3934. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3935. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3936. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3937. return cell;
  3938. }
  3939. - (void)setTableViewFooter
  3940. {
  3941. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3942. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3943. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3944. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3945. UIFont *appFont = [UIFont systemFontOfSize:12];
  3946. footerLabel.font = appFont;
  3947. footerLabel.textColor = [UIColor grayColor];
  3948. footerLabel.backgroundColor = [UIColor clearColor];
  3949. footerLabel.textAlignment = NSTextAlignmentCenter;
  3950. NSString *folders;
  3951. NSString *files;
  3952. NSString *footerText;
  3953. if (_sectionDataSource.directories > 1) {
  3954. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3955. } else if (_sectionDataSource.directories == 1){
  3956. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3957. } else {
  3958. folders = @"";
  3959. }
  3960. if (_sectionDataSource.files > 1) {
  3961. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3962. } else if (_sectionDataSource.files == 1){
  3963. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3964. } else {
  3965. files = @"";
  3966. }
  3967. if ([folders isEqualToString:@""]) {
  3968. footerText = files;
  3969. } else if ([files isEqualToString:@""]) {
  3970. footerText = folders;
  3971. } else {
  3972. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3973. }
  3974. footerLabel.text = footerText;
  3975. [footerView addSubview:footerLabel];
  3976. [self.tableView setTableFooterView:footerView];
  3977. }
  3978. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3979. {
  3980. NSString *textMessage;
  3981. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3982. // se non può essere selezionata deseleziona
  3983. if ([cell isEditing] == NO)
  3984. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3985. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3986. if (self.tableView.editing) {
  3987. [self setTitle];
  3988. return;
  3989. }
  3990. // test crash
  3991. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3992. if (indexPath.row >= [metadatas count]) return;
  3993. // settiamo il record file.
  3994. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3995. //
  3996. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3997. // se è in corso una sessione
  3998. if ([_metadata.session length] > 0) return;
  3999. if (_metadata.errorPasscode) {
  4000. // se UUID è nil lo sta ancora caricando quindi esci
  4001. if (!_metadata.uuid) return;
  4002. // esiste un hint ??
  4003. CCCrypto *crypto = [[CCCrypto alloc] init];
  4004. NSString *hint = [crypto getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  4005. // qui !! la richiesta della nuova passcode
  4006. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  4007. // stesso UUID ... la password è stata modificata !!!!!!
  4008. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  4009. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  4010. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  4011. [alertView show];
  4012. } else {
  4013. // UUID diverso.
  4014. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  4015. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  4016. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  4017. [alertView show];
  4018. }
  4019. // chiediamo la passcode e ricarichiamo tutto.
  4020. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4021. viewController.delegate = self;
  4022. viewController.fromType = CCBKPasscodeFromPasscode;
  4023. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4024. viewController.passcodeInputView.maximumLength = 64;
  4025. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4026. viewController.inputViewTitlePassword = NO;
  4027. viewController.title = _brand_;
  4028. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4029. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_CRYPTOCLOUD;
  4030. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4031. [self presentViewController:navigationController animated:YES completion:nil];
  4032. }
  4033. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  4034. if (_metadata.cryptated && [_metadata.title length] == 0) {
  4035. NSString* selector;
  4036. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  4037. else selector = selectorLoadPlist;
  4038. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4039. return;
  4040. }
  4041. // se il plist è caricato ed è un modello aprilo
  4042. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  4043. // file
  4044. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  4045. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  4046. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  4047. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  4048. } else {
  4049. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  4050. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  4051. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  4052. }
  4053. }
  4054. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  4055. }
  4056. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  4057. {
  4058. [self setTitle];
  4059. }
  4060. #pragma --------------------------------------------------------------------------------------------
  4061. #pragma mark ===== Synchronize Folder Cell =====
  4062. #pragma --------------------------------------------------------------------------------------------
  4063. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  4064. {
  4065. BOOL cryptated = NO;
  4066. CCCellMain *cell;
  4067. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  4068. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4069. if (recordMetadata.directory == NO)
  4070. continue;
  4071. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  4072. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  4073. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  4074. cryptated = recordMetadata.cryptated;
  4075. break;
  4076. }
  4077. }
  4078. if (!cell)
  4079. return;
  4080. if (animation) {
  4081. NSURL *myURL;
  4082. if (cryptated)
  4083. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4084. else
  4085. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4086. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  4087. } else {
  4088. cell.synchronizedImageView.image = nil;
  4089. }
  4090. }
  4091. #pragma --------------------------------------------------------------------------------------------
  4092. #pragma mark ===== Navigation ====
  4093. #pragma --------------------------------------------------------------------------------------------
  4094. - (BOOL)shouldPerformSegue:(NSString *)serverUrl
  4095. {
  4096. // if background return
  4097. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4098. if (self.view.window == NO)
  4099. return NO;
  4100. // Collapsed ma siamo già in detail esci
  4101. if (self.splitViewController.isCollapsed)
  4102. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4103. // Video in esecuzione esci
  4104. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4105. return YES;
  4106. }
  4107. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4108. {
  4109. id viewController = segue.destinationViewController;
  4110. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4111. UINavigationController *nav = viewController;
  4112. _detailViewController = (CCDetail *)nav.topViewController;
  4113. } else {
  4114. _detailViewController = segue.destinationViewController;
  4115. }
  4116. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  4117. for (NSString *fileID in _sectionDataSource.allFileID) {
  4118. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4119. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4120. [allRecordsDataSourceImagesVideos addObject:metadata];
  4121. }
  4122. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4123. _detailViewController.metadataDetail = _metadataSegue;
  4124. _detailViewController.dateFilterQuery = nil;
  4125. _detailViewController.isCameraUpload = NO;
  4126. [_detailViewController setTitle:_metadata.fileNamePrint];
  4127. }
  4128. // can i go to next viewcontroller
  4129. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4130. {
  4131. NSString *nomeDir;
  4132. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4133. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4134. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4135. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4136. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4137. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4138. viewController.delegate = self;
  4139. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4140. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4141. viewController.inputViewTitlePassword = YES;
  4142. if ([CCUtility getSimplyBlockCode]) {
  4143. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4144. viewController.passcodeInputView.maximumLength = 6;
  4145. } else {
  4146. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4147. viewController.passcodeInputView.maximumLength = 64;
  4148. }
  4149. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  4150. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4151. viewController.touchIDManager = touchIDManager;
  4152. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4153. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4154. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_CRYPTOCLOUD;
  4155. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4156. [self presentViewController:navController animated:YES completion:nil];
  4157. return;
  4158. }
  4159. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4160. else nomeDir = _metadata.fileName;
  4161. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4162. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4163. if (viewController.isViewLoaded == false) {
  4164. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4165. viewController.isFolderEncrypted = _metadata.cryptated;
  4166. viewController.serverUrl = serverUrlPush;
  4167. viewController.titleMain = _metadata.fileNamePrint;
  4168. viewController.textBackButton = _titleMain;
  4169. // save self
  4170. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4171. }
  4172. // OFF SearchBar
  4173. [viewController cancelSearchBar];
  4174. [self.navigationController pushViewController:viewController animated:YES];
  4175. }
  4176. }
  4177. @end