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