CCMain.m 250 KB

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