CCMain.m 257 KB

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