CCMain.m 257 KB

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