CCMain.m 238 KB

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