CCMain.m 239 KB

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