CCMain.m 240 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435
  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. }];
  1199. [alertController addAction:cancelAction];
  1200. [alertController addAction:overwriteAction];
  1201. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  1202. alertWindow.rootViewController = [[UIViewController alloc]init];
  1203. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  1204. [alertWindow makeKeyAndVisible];
  1205. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  1206. } else {
  1207. // Send to Upload Queue
  1208. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1209. }
  1210. }
  1211. }
  1212. #pragma --------------------------------------------------------------------------------------------
  1213. #pragma mark ==== Read File ====
  1214. #pragma --------------------------------------------------------------------------------------------
  1215. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1216. {
  1217. // Check Active Account
  1218. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1219. return;
  1220. // Unauthorized
  1221. if (errorCode == kOCErrorServerUnauthorized)
  1222. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1223. }
  1224. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1225. {
  1226. // Check Active Account
  1227. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1228. return;
  1229. // Read Folder
  1230. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1231. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1232. // Change etag, read folder
  1233. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1234. [self readFolder:metadataNet.serverUrl];
  1235. }
  1236. }
  1237. }
  1238. - (void)readFileReloadFolder
  1239. {
  1240. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  1241. return;
  1242. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1243. metadataNet.action = actionReadFile;
  1244. metadataNet.priority = NSOperationQueuePriorityHigh;
  1245. metadataNet.selector = selectorReadFileReloadFolder;
  1246. metadataNet.serverUrl = _serverUrl;
  1247. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1248. }
  1249. #pragma --------------------------------------------------------------------------------------------
  1250. #pragma mark ==== Read Folder ====
  1251. #pragma --------------------------------------------------------------------------------------------
  1252. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1253. {
  1254. // stoprefresh
  1255. [_refreshControl endRefreshing];
  1256. _loadingFolder = NO;
  1257. // Check Active Account
  1258. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1259. return;
  1260. // Unauthorized
  1261. if (errorCode == kOCErrorServerUnauthorized) {
  1262. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1263. } else {
  1264. [self tableViewReloadData];
  1265. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1266. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1267. [self reloadDatasource:metadataNet.serverUrl];
  1268. }
  1269. }
  1270. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1271. {
  1272. // stoprefresh
  1273. [_refreshControl endRefreshing];
  1274. // Check Active Account
  1275. if (![metadataNet.account isEqualToString:metadataNet.account])
  1276. return;
  1277. // save metadataFolder
  1278. _metadataFolder = metadataFolder;
  1279. // save father e update permission
  1280. if(!_isSearchMode && metadataFolder)
  1281. _fatherPermission = metadataFolder.permissions;
  1282. NSArray *recordsInSessions;
  1283. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1284. if (_isSearchMode) {
  1285. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1286. } else {
  1287. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  1288. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1289. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1290. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1291. }
  1292. for (tableMetadata *metadata in metadatas) {
  1293. // verify if the record is in download/upload progress
  1294. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1295. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", appDelegate.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1296. // is in Download or Upload
  1297. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1298. continue;
  1299. }
  1300. }
  1301. // Insert in Array
  1302. [metadatasToInsertInDB addObject:metadata];
  1303. }
  1304. // insert in Database
  1305. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1306. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1307. // File is changed ??
  1308. if (!_isSearchMode && metadatasToInsertInDB)
  1309. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  1310. });
  1311. // Search Mode
  1312. if (_isSearchMode) {
  1313. // Fix managed -> Unmanaged _searchResultMetadatas
  1314. if (metadatasToInsertInDB)
  1315. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1316. [self reloadDatasource:metadataNet.serverUrl];
  1317. }
  1318. // this is the same directory
  1319. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1320. // reload
  1321. [self reloadDatasource:metadataNet.serverUrl];
  1322. // Enable change user
  1323. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1324. _loadingFolder = NO;
  1325. [self tableViewReloadData];
  1326. }
  1327. // E2EE Is encrypted folder get metadata
  1328. if (_metadataFolder.e2eEncrypted) {
  1329. // Read Metadata
  1330. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1331. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1332. NSString *metadata;
  1333. NSError *error = [[NCNetworkingSync sharedManager] getEndToEndMetadata:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:metadataFolder.fileID metadata:&metadata];
  1334. dispatch_async(dispatch_get_main_queue(), ^{
  1335. if (error) {
  1336. if (error.code != 404)
  1337. [appDelegate messageNotification:@"_error_e2ee_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1338. } else {
  1339. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:appDelegate.activeAccount] serverUrl:self.serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl] == false)
  1340. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1341. else
  1342. [self reloadDatasource];
  1343. }
  1344. });
  1345. });
  1346. } else {
  1347. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1348. }
  1349. }
  1350. // rewrite title
  1351. [self setTitle];
  1352. }
  1353. - (void)readFolder:(NSString *)serverUrl
  1354. {
  1355. // init control
  1356. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  1357. [_refreshControl endRefreshing];
  1358. return;
  1359. }
  1360. // Search Mode
  1361. if (_isSearchMode) {
  1362. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1363. _searchFileName = @""; // forced reload searchg
  1364. [self updateSearchResultsForSearchController:self.searchController];
  1365. return;
  1366. }
  1367. _loadingFolder = YES;
  1368. [self tableViewReloadData];
  1369. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  1370. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1371. metadataNet.action = actionReadFolder;
  1372. metadataNet.date = [NSDate date];
  1373. metadataNet.depth = @"1";
  1374. metadataNet.directoryID = directory.directoryID;
  1375. metadataNet.priority = NSOperationQueuePriorityHigh;
  1376. metadataNet.selector = selectorReadFolder;
  1377. metadataNet.serverUrl = serverUrl;
  1378. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1379. }
  1380. #pragma mark -
  1381. #pragma --------------------------------------------------------------------------------------------
  1382. #pragma mark ===== Search =====
  1383. #pragma --------------------------------------------------------------------------------------------
  1384. - (void)searchEnabled:(BOOL)enabled
  1385. {
  1386. if (enabled) {
  1387. if (self.tableView.tableHeaderView != nil)
  1388. return;
  1389. self.definesPresentationContext = YES;
  1390. self.searchController.searchResultsUpdater = self;
  1391. self.searchController.dimsBackgroundDuringPresentation = NO;
  1392. self.searchController.searchBar.translucent = NO;
  1393. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1394. [self.searchController.searchBar sizeToFit];
  1395. self.searchController.searchBar.delegate = self;
  1396. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1397. self.searchController.searchBar.backgroundImage = [UIImage new];
  1398. self.tableView.tableHeaderView = self.searchController.searchBar;
  1399. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1400. } else {
  1401. self.tableView.tableHeaderView = nil;
  1402. }
  1403. }
  1404. - (void)searchStartTimer
  1405. {
  1406. NSString *home = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1407. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1408. _noFilesSearchTitle = @"";
  1409. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1410. [self.tableView reloadEmptyDataSet];
  1411. }
  1412. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1413. {
  1414. // Color text "Cancel"
  1415. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1416. _isSearchMode = YES;
  1417. [self deleteRefreshControl];
  1418. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1419. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1420. _searchFileName = fileName;
  1421. // First : filter
  1422. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1423. if (!directoryID) return;
  1424. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNameView CONTAINS[cd] %@", directoryID, appDelegate.activeAccount, fileName];
  1425. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1426. [_searchResultMetadatas removeAllObjects];
  1427. for (tableMetadata *record in records)
  1428. [_searchResultMetadatas addObject:record];
  1429. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1430. metadataNet.account = appDelegate.activeAccount;
  1431. metadataNet.directoryID = directoryID;
  1432. metadataNet.selector = selectorSearch;
  1433. metadataNet.serverUrl = _serverUrl;
  1434. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1435. // Version >= 12
  1436. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1437. [_timerWaitInput invalidate];
  1438. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1439. }
  1440. }
  1441. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1442. [self reloadDatasource];
  1443. }
  1444. }
  1445. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1446. {
  1447. [self cancelSearchBar];
  1448. [self readFolder:_serverUrl];
  1449. }
  1450. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1451. {
  1452. // Check Active Account
  1453. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1454. return;
  1455. // Unauthorized
  1456. if (errorCode == kOCErrorServerUnauthorized)
  1457. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1458. else
  1459. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1460. _searchFileName = @"";
  1461. }
  1462. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1463. {
  1464. // Check Active Account
  1465. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1466. return;
  1467. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1468. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1469. }
  1470. - (void)cancelSearchBar
  1471. {
  1472. if (self.searchController.active) {
  1473. [self.searchController setActive:NO];
  1474. [self createRefreshControl];
  1475. _isSearchMode = NO;
  1476. _searchFileName = @"";
  1477. _dateReadDataSource = nil;
  1478. _searchResultMetadatas = [NSMutableArray new];
  1479. [self reloadDatasource];
  1480. }
  1481. //[self setNeedsStatusBarAppearanceUpdate];
  1482. }
  1483. #pragma mark -
  1484. #pragma --------------------------------------------------------------------------------------------
  1485. #pragma mark ===== Delete File or Folder =====
  1486. #pragma --------------------------------------------------------------------------------------------
  1487. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1488. {
  1489. // Unauthorized
  1490. if (errorCode == kOCErrorServerUnauthorized)
  1491. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1492. NSLog(@"[LOG] Delete File failure error %d, %@", (int)errorCode, message);
  1493. [self deleteFileOrFolderSuccess:metadataNet];
  1494. }
  1495. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1496. {
  1497. [_queueSelector removeObject:metadataNet.selector];
  1498. if ([_queueSelector count] == 0) {
  1499. [_hud hideHud];
  1500. // next
  1501. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1502. if ([_selectedFileIDsMetadatas count] > 0) {
  1503. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1504. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1505. } else {
  1506. // End Select Table View
  1507. [self tableViewSelect:NO];
  1508. // Reload
  1509. if (_isSearchMode)
  1510. [self readFolder:metadataNet.serverUrl];
  1511. else
  1512. [self reloadDatasource:metadataNet.serverUrl];
  1513. }
  1514. }
  1515. }
  1516. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1517. {
  1518. [_queueSelector addObject:selectorDelete];
  1519. // E2EE LOCK
  1520. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", appDelegate.activeAccount, metadata.fileName]];
  1521. if (tableE2eEncryption) {
  1522. }
  1523. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:_hud hudTitled:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile]];
  1524. }
  1525. - (void)deleteFile
  1526. {
  1527. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1528. return;
  1529. [_queueSelector removeAllObjects];
  1530. if ([_selectedFileIDsMetadatas count] > 0) {
  1531. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1532. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1533. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1534. } else {
  1535. _numSelectedFileIDsMetadatas = 1;
  1536. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1537. }
  1538. }
  1539. #pragma --------------------------------------------------------------------------------------------
  1540. #pragma mark ===== Rename / Move =====
  1541. #pragma --------------------------------------------------------------------------------------------
  1542. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1543. {
  1544. [self readFolder:metadataNet.serverUrl];
  1545. }
  1546. - (void)renameFile:(NSArray *)arguments
  1547. {
  1548. tableMetadata* metadata = [arguments objectAtIndex:0];
  1549. NSString *fileName = [arguments objectAtIndex:1];
  1550. // E2EE
  1551. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  1552. // verify if exists the new fileName
  1553. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@ AND fileName = %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1554. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1555. return;
  1556. }
  1557. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1558. NSString *token;
  1559. NSError *error = [[NCNetworkingSync sharedManager] sendEndToEndMetadataOnServerUrl:self.serverUrl account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileNameRename:metadata.fileName fileNameNewRename:fileName token:&token];
  1560. if (error) {
  1561. dispatch_async(dispatch_get_main_queue(), ^{
  1562. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1563. });
  1564. } else {
  1565. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1566. }
  1567. // Unlock
  1568. if (token) {
  1569. NSError *error = [[NCNetworkingSync sharedManager] unlockEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadataFolder.fileID token:token];
  1570. if (error) {
  1571. dispatch_async(dispatch_get_main_queue(), ^{
  1572. [appDelegate messageNotification:@"_error_e2ee_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1573. });
  1574. }
  1575. }
  1576. dispatch_async(dispatch_get_main_queue(), ^{
  1577. [self reloadDatasource];
  1578. });
  1579. });
  1580. } else {
  1581. // Plain
  1582. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1583. }
  1584. }
  1585. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1586. {
  1587. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1588. [_hud hideHud];
  1589. if (message && errorCode != kOCErrorServerUnauthorized)
  1590. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1591. // End Select Table View
  1592. [self tableViewSelect:NO];
  1593. // reload Datasource
  1594. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1595. [self readFolder:metadataNet.serverUrl];
  1596. else
  1597. [self reloadDatasource];
  1598. }
  1599. }
  1600. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1601. {
  1602. [_queueSelector removeObject:metadataNet.selector];
  1603. if ([_queueSelector count] == 0) {
  1604. [_hud hideHud];
  1605. NSString *fileName = metadataNet.fileName;
  1606. NSString *directoryID = metadataNet.directoryID;
  1607. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1608. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1609. if (!serverUrlTo) return;
  1610. // FILE -> Metadata
  1611. if (metadataNet.directory == NO)
  1612. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1613. // DIRECTORY -> Directory - CCMetadata
  1614. if (metadataNet.directory == YES) {
  1615. // delete all dir / subdir
  1616. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1617. // move metadata
  1618. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1619. // Add new directory
  1620. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1621. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1622. }
  1623. // next
  1624. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1625. if ([_selectedFileIDsMetadatas count] > 0) {
  1626. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1627. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1628. } else {
  1629. // End Select Table View
  1630. [self tableViewSelect:NO];
  1631. // reload Datasource
  1632. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1633. [self readFolder:metadataNet.serverUrl];
  1634. else
  1635. [self reloadDatasource];
  1636. }
  1637. }
  1638. }
  1639. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1640. {
  1641. tableMetadata *metadata = [arguments objectAtIndex:0];
  1642. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1643. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1644. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1645. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1646. if (!serverUrl) return;
  1647. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1648. if (!directoryIDTo) return;
  1649. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1650. NSArray *items;
  1651. NSError *error = [[NCNetworkingSync sharedManager] readFile:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName] user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword items:&items];
  1652. if(!error) {
  1653. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1654. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1655. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1656. }];
  1657. [alert addAction:ok];
  1658. [self presentViewController:alert animated:YES completion:nil];
  1659. // End Select Table View
  1660. [self tableViewSelect:NO];
  1661. // reload Datasource
  1662. [self readFileReloadFolder];
  1663. });
  1664. return;
  1665. }
  1666. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1667. metadataNet.action = actionMoveFileOrFolder;
  1668. metadataNet.directory = metadata.directory;
  1669. metadataNet.fileID = metadata.fileID;
  1670. metadataNet.directoryID = metadata.directoryID;
  1671. metadataNet.directoryIDTo = directoryIDTo;
  1672. metadataNet.fileName = metadata.fileName;
  1673. metadataNet.fileNameView = metadata.fileNameView;
  1674. metadataNet.fileNameTo = metadata.fileName;
  1675. metadataNet.etag = metadata.etag;
  1676. metadataNet.selector = selectorMove;
  1677. metadataNet.serverUrl = serverUrl;
  1678. metadataNet.serverUrlTo = serverUrlTo;
  1679. [_queueSelector addObject:metadataNet.selector];
  1680. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1681. dispatch_async(dispatch_get_main_queue(), ^{
  1682. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1683. });
  1684. });
  1685. }
  1686. // DELEGATE : Move
  1687. - (void)dismissMove
  1688. {
  1689. [self reloadDatasource];
  1690. }
  1691. // DELEGATE : Move
  1692. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1693. {
  1694. [_queueSelector removeAllObjects];
  1695. // E2EE DENIED
  1696. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1697. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1698. return;
  1699. }
  1700. if ([_selectedFileIDsMetadatas count] > 0) {
  1701. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1702. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1703. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1704. } else {
  1705. _numSelectedFileIDsMetadatas = 1;
  1706. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1707. }
  1708. }
  1709. - (void)moveOpenWindow:(NSArray *)indexPaths
  1710. {
  1711. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1712. return;
  1713. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1714. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1715. viewController.delegate = self;
  1716. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1717. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1718. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1719. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1720. viewController.networkingOperationQueue = appDelegate.netQueue;
  1721. // E2EE
  1722. viewController.includeDirectoryE2EEncryption = NO;
  1723. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1724. [self presentViewController:navigationController animated:YES completion:nil];
  1725. }
  1726. #pragma --------------------------------------------------------------------------------------------
  1727. #pragma mark ===== Create folder =====
  1728. #pragma --------------------------------------------------------------------------------------------
  1729. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1730. {
  1731. // Unauthorized
  1732. if (errorCode == kOCErrorServerUnauthorized)
  1733. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1734. if (message && errorCode != kOCErrorServerUnauthorized)
  1735. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1736. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1737. [self reloadDatasource];
  1738. // We are in directory fail ?
  1739. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1740. if (vc)
  1741. [vc.navigationController popViewControllerAnimated:YES];
  1742. }
  1743. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1744. {
  1745. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1746. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1747. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1748. if (metadata) {
  1749. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1750. metadata.fileID = metadataNet.fileID;
  1751. metadata.date = metadataNet.date;
  1752. metadata.permissions = @"RDNVCK";
  1753. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1754. [self reloadDatasource];
  1755. } else {
  1756. [self readFileReloadFolder];
  1757. }
  1758. }
  1759. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1760. {
  1761. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1762. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1763. if (![fileNameFolder length]) return;
  1764. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1765. if (!directoryID) return;
  1766. metadataNet.action = actionCreateFolder;
  1767. metadataNet.directoryID = directoryID;
  1768. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1769. metadataNet.fileName = fileNameFolder;
  1770. metadataNet.selector = selectorCreateFolder;
  1771. metadataNet.serverUrl = serverUrl;
  1772. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1773. // Create Directory on metadata
  1774. 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];
  1775. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1776. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1777. [self reloadDatasource];
  1778. }
  1779. #pragma --------------------------------------------------------------------------------------------
  1780. #pragma mark ===== Progress & Task Button =====
  1781. #pragma --------------------------------------------------------------------------------------------
  1782. - (void)triggerProgressTask:(NSNotification *)notification
  1783. {
  1784. NSDictionary *dict = notification.userInfo;
  1785. NSString *fileID = [dict valueForKey:@"fileID"];
  1786. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1787. float progress = [[dict valueForKey:@"progress"] floatValue];
  1788. // Check
  1789. if (!fileID || [fileID isEqualToString: @""])
  1790. return;
  1791. [appDelegate.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1792. if (![serverUrl isEqualToString:_serverUrl])
  1793. return;
  1794. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1795. if ([self indexPathIsValid:indexPath]) {
  1796. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1797. cell.progressView.progressTintColor = [UIColor blackColor];
  1798. cell.progressView.hidden = NO;
  1799. [cell.progressView setProgress:progress];
  1800. }
  1801. }
  1802. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1803. {
  1804. UITouch * touch = [[event allTouches] anyObject];
  1805. CGPoint location = [touch locationInView:self.tableView];
  1806. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1807. if ([self indexPathIsValid:indexPath]) {
  1808. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1809. if (metadataSection) {
  1810. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1811. if (metadata)
  1812. [self reloadTaskButton:metadata];
  1813. }
  1814. }
  1815. }
  1816. - (void)reloadTaskButton:(tableMetadata *)metadata
  1817. {
  1818. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1819. __block NSURLSessionTask *findTask;
  1820. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1821. NSString *fileID = metadata.fileID;
  1822. // DOWNLOAD
  1823. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1824. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1825. for (NSURLSessionUploadTask *task in downloadTasks)
  1826. if (task.taskIdentifier == sessionTaskIdentifier) {
  1827. findTask = task;
  1828. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1829. [task cancel];
  1830. }
  1831. if (!findTask) {
  1832. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1833. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1834. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1835. }
  1836. }];
  1837. }
  1838. // UPLOAD
  1839. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1840. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1841. for (NSURLSessionUploadTask *task in uploadTasks)
  1842. if (task.taskIdentifier == sessionTaskIdentifier) {
  1843. findTask = task;
  1844. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1845. [task cancel];
  1846. }
  1847. if (!findTask) {
  1848. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1849. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1850. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1851. }
  1852. }];
  1853. }
  1854. }
  1855. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1856. {
  1857. UITouch * touch = [[event allTouches] anyObject];
  1858. CGPoint location = [touch locationInView:self.tableView];
  1859. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1860. if ([self indexPathIsValid:indexPath]) {
  1861. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1862. if (metadataSection) {
  1863. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1864. if (metadata)
  1865. [self cancelTaskButton:metadata reloadTable:YES];
  1866. }
  1867. }
  1868. }
  1869. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1870. {
  1871. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1872. __block NSURLSessionTask *findTask;
  1873. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1874. NSString *fileID = metadata.fileID;
  1875. // DOWNLOAD
  1876. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1877. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1878. for (NSURLSessionTask *task in downloadTasks)
  1879. if (task.taskIdentifier == sessionTaskIdentifier) {
  1880. findTask = task;
  1881. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1882. [task cancel];
  1883. }
  1884. if (!findTask) {
  1885. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1886. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1887. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1888. }
  1889. }];
  1890. }
  1891. // UPLOAD
  1892. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1893. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1894. for (NSURLSessionUploadTask *task in uploadTasks)
  1895. if (task.taskIdentifier == sessionTaskIdentifier) {
  1896. findTask = task;
  1897. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1898. [task cancel];
  1899. }
  1900. if (!findTask) {
  1901. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1902. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1903. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1904. }
  1905. }];
  1906. }
  1907. }
  1908. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1909. {
  1910. UITouch * touch = [[event allTouches] anyObject];
  1911. CGPoint location = [touch locationInView:self.tableView];
  1912. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1913. if ([self indexPathIsValid:indexPath]) {
  1914. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1915. if (metadataSection) {
  1916. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1917. if (metadata)
  1918. [self stopTaskButton:metadata];
  1919. }
  1920. }
  1921. }
  1922. - (void)stopTaskButton:(tableMetadata *)metadata
  1923. {
  1924. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1925. __block NSURLSessionTask *findTask;
  1926. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1927. NSString *fileID = metadata.fileID;
  1928. // UPLOAD
  1929. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1930. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1931. for (NSURLSessionUploadTask *task in uploadTasks)
  1932. if (task.taskIdentifier == sessionTaskIdentifier) {
  1933. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1934. findTask = task;
  1935. [task cancel];
  1936. }
  1937. if (!findTask) {
  1938. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1939. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1940. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1941. }
  1942. }];
  1943. }
  1944. }
  1945. #pragma --------------------------------------------------------------------------------------------
  1946. #pragma mark ===== Shared =====
  1947. #pragma --------------------------------------------------------------------------------------------
  1948. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1949. {
  1950. [_hud hideHud];
  1951. // Check Active Account
  1952. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1953. return;
  1954. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1955. if (result) {
  1956. appDelegate.sharesLink = result[0];
  1957. appDelegate.sharesUserAndGroup = result[1];
  1958. }
  1959. // Notify Shares View
  1960. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1961. if (openWindow) {
  1962. if (_shareOC) {
  1963. [_shareOC reloadData];
  1964. } else {
  1965. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1966. // Apriamo la view
  1967. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1968. _shareOC.delegate = self;
  1969. _shareOC.metadata = metadata;
  1970. _shareOC.serverUrl = metadataNet.serverUrl;
  1971. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1972. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1973. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1974. [self presentViewController:_shareOC animated:YES completion:nil];
  1975. }
  1976. }
  1977. [self tableViewReloadData];
  1978. }
  1979. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1980. {
  1981. [_hud hideHud];
  1982. // Check Active Account
  1983. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1984. return;
  1985. // Unauthorized
  1986. if (errorCode == kOCErrorServerUnauthorized)
  1987. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1988. else
  1989. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1990. if (_shareOC)
  1991. [_shareOC reloadData];
  1992. [self tableViewReloadData];
  1993. }
  1994. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1995. {
  1996. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1997. metadataNet.action = actionShare;
  1998. metadataNet.fileID = metadata.fileID;
  1999. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  2000. metadataNet.fileNameView = metadata.fileNameView;
  2001. metadataNet.password = password;
  2002. metadataNet.selector = selectorShare;
  2003. metadataNet.serverUrl = serverUrl;
  2004. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2005. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2006. }
  2007. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2008. {
  2009. [_hud hideHud];
  2010. // Check Active Account
  2011. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  2012. return;
  2013. // rimuoviamo la condivisione da db
  2014. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2015. if (result) {
  2016. appDelegate.sharesLink = result[0];
  2017. appDelegate.sharesUserAndGroup = result[1];
  2018. }
  2019. if (_shareOC)
  2020. [_shareOC reloadData];
  2021. [self tableViewReloadData];
  2022. }
  2023. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2024. {
  2025. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2026. metadataNet.action = actionUnShare;
  2027. metadataNet.fileID = metadata.fileID;
  2028. metadataNet.fileName = metadata.fileName;
  2029. metadataNet.fileNameView = metadata.fileNameView;
  2030. metadataNet.selector = selectorUnshare;
  2031. metadataNet.serverUrl = serverUrl;
  2032. metadataNet.share = share;
  2033. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2034. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2035. }
  2036. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2037. {
  2038. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2039. metadataNet.action = actionUpdateShare;
  2040. metadataNet.fileID = metadata.fileID;
  2041. metadataNet.expirationTime = expirationTime;
  2042. metadataNet.password = password;
  2043. metadataNet.selector = selectorUpdateShare;
  2044. metadataNet.serverUrl = serverUrl;
  2045. metadataNet.share = share;
  2046. metadataNet.sharePermission = permission;
  2047. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2048. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2049. }
  2050. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2051. {
  2052. [_hud hideHud];
  2053. // Check Active Account
  2054. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  2055. return;
  2056. if (_shareOC)
  2057. [_shareOC reloadUserAndGroup:items];
  2058. }
  2059. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2060. {
  2061. [_hud hideHud];
  2062. // Check Active Account
  2063. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  2064. return;
  2065. // Unauthorized
  2066. if (errorCode == kOCErrorServerUnauthorized)
  2067. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  2068. else
  2069. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2070. }
  2071. - (void)getUserAndGroup:(NSString *)find
  2072. {
  2073. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2074. metadataNet.action = actionGetUserAndGroup;
  2075. metadataNet.options = find;
  2076. metadataNet.selector = selectorGetUserAndGroup;
  2077. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2078. [_hud visibleIndeterminateHud];
  2079. }
  2080. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2081. {
  2082. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2083. metadataNet.action = actionShareWith;
  2084. metadataNet.fileID = metadata.fileID;
  2085. metadataNet.directoryID = directoryID;
  2086. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  2087. metadataNet.fileNameView = metadata.fileNameView;
  2088. metadataNet.serverUrl = serverUrl;
  2089. metadataNet.selector = selectorShare;
  2090. metadataNet.share = user;
  2091. metadataNet.shareeType = shareeType;
  2092. metadataNet.sharePermission = permission;
  2093. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2094. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2095. }
  2096. - (void)openWindowShare:(tableMetadata *)metadata
  2097. {
  2098. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2099. if (!serverUrl) return;
  2100. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2101. metadataNet.action = actionReadShareServer;
  2102. metadataNet.fileID = metadata.fileID;
  2103. metadataNet.fileName = metadata.fileName;
  2104. metadataNet.fileNameView = metadata.fileNameView;
  2105. metadataNet.selector = selectorOpenWindowShare;
  2106. metadataNet.serverUrl = serverUrl;
  2107. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2108. [_hud visibleIndeterminateHud];
  2109. }
  2110. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2111. {
  2112. CGPoint location = [tapGesture locationInView:self.tableView];
  2113. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2114. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2115. if (metadata)
  2116. [self openWindowShare:metadata];
  2117. }
  2118. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2119. {
  2120. CGPoint location = [tapGesture locationInView:self.tableView];
  2121. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2122. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2123. if (metadata) {
  2124. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2125. vc.metadata = metadata;
  2126. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2127. [self presentViewController:vc animated:YES completion:nil];
  2128. }
  2129. }
  2130. #pragma --------------------------------------------------------------------------------------------
  2131. #pragma mark ===== Favorite =====
  2132. #pragma --------------------------------------------------------------------------------------------
  2133. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2134. {
  2135. // Check Active Account
  2136. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  2137. return;
  2138. _dateReadDataSource = nil;
  2139. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2140. if (_isSearchMode)
  2141. [self readFolder:metadataNet.serverUrl];
  2142. else
  2143. [self reloadDatasource:metadataNet.serverUrl];
  2144. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2145. if (metadata.directory && metadata.favorite) {
  2146. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2147. [appDelegate.activeFavorites addFavoriteFolder:dir];
  2148. }
  2149. }
  2150. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2151. {
  2152. // Unauthorized
  2153. if (errorCode == kOCErrorServerUnauthorized)
  2154. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  2155. NSLog(@"[LOG] Setting Favorite failure error %d, %@", (int)errorCode, message);
  2156. }
  2157. - (void)addFavorite:(tableMetadata *)metadata
  2158. {
  2159. if (metadata.directory) {
  2160. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2161. } else {
  2162. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2163. if (serverUrl)
  2164. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2165. }
  2166. }
  2167. - (void)removeFavorite:(tableMetadata *)metadata
  2168. {
  2169. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2170. }
  2171. #pragma --------------------------------------------------------------------------------------------
  2172. #pragma mark ===== E2E Encryption =====
  2173. #pragma --------------------------------------------------------------------------------------------
  2174. - (void)unlockEndToEndFolderEncryptedSuccess:(CCMetadataNet *)metadataNet
  2175. {
  2176. [[NCManageDatabase sharedInstance] setDirectoryE2ETokenLockWithFileID:metadataNet.fileID token:@""];
  2177. [appDelegate messageNotification:@"_success_" description:@"_e2e_remove_folder_lock_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2178. }
  2179. - (void)unlockEndToEndFolderEncryptedFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2180. {
  2181. if (errorCode == 404)
  2182. [[NCManageDatabase sharedInstance] setDirectoryE2ETokenLockWithFileID:metadataNet.fileID token:@""];
  2183. [appDelegate messageNotification:@"_error_e2ee_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2184. }
  2185. #pragma --------------------------------------------------------------------------------------------
  2186. #pragma mark ===== Open in... =====
  2187. #pragma --------------------------------------------------------------------------------------------
  2188. - (void)openIn:(tableMetadata *)metadata
  2189. {
  2190. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2191. if (!serverUrl) return;
  2192. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2193. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2194. if ([self indexPathIsValid:indexPath])
  2195. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2196. }
  2197. #pragma --------------------------------------------------------------------------------------------
  2198. #pragma mark ===== Remove Local File =====
  2199. #pragma --------------------------------------------------------------------------------------------
  2200. - (void)removeLocalFile:(tableMetadata *)metadata
  2201. {
  2202. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2203. if (!serverUrl) return;
  2204. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2205. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] error:nil];
  2206. [self reloadDatasource:serverUrl];
  2207. }
  2208. #pragma --------------------------------------------------------------------------------------------
  2209. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2210. #pragma --------------------------------------------------------------------------------------------
  2211. - (void)orderTable:(NSString *)order
  2212. {
  2213. [CCUtility setOrderSettings:order];
  2214. // Clear data-read of DataSource
  2215. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2216. }
  2217. - (void)ascendingTable:(BOOL)ascending
  2218. {
  2219. [CCUtility setAscendingSettings:ascending];
  2220. // Clear data-read of DataSource
  2221. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2222. }
  2223. - (void)directoryOnTop:(BOOL)directoryOnTop
  2224. {
  2225. [CCUtility setDirectoryOnTop:directoryOnTop];
  2226. // Clear data-read of DataSource
  2227. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2228. }
  2229. - (void)tableGroupBy:(NSString *)groupBy
  2230. {
  2231. [CCUtility setGroupBySettings:groupBy];
  2232. // Clear data-read of DataSource
  2233. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2234. }
  2235. #pragma --------------------------------------------------------------------------------------------
  2236. #pragma mark ==== Menu LOGO ====
  2237. #pragma --------------------------------------------------------------------------------------------
  2238. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2239. {
  2240. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  2241. return;
  2242. // Brand
  2243. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2244. return;
  2245. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2246. NSMutableArray *menuArray = [NSMutableArray new];
  2247. for (NSString *account in listAccount) {
  2248. if ([account isEqualToString:appDelegate.activeAccount]) continue;
  2249. CCMenuItem *item = [[CCMenuItem alloc] init];
  2250. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2251. item.argument = account;
  2252. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ ", account]];
  2253. NSString *directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  2254. UIImage *avatar = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/avatar.png", directoryUser]];
  2255. if (avatar) {
  2256. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  2257. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  2258. CGSize imageSize = avatarImageView.bounds.size;
  2259. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  2260. CGContextRef context = UIGraphicsGetCurrentContext();
  2261. [avatarImageView.layer renderInContext:context];
  2262. avatar = UIGraphicsGetImageFromCurrentImageContext();
  2263. UIGraphicsEndImageContext();
  2264. } else {
  2265. avatar = [UIImage imageNamed:@"menuLogoUser"];
  2266. }
  2267. item.image = avatar;
  2268. item.target = self;
  2269. item.action = @selector(changeDefaultAccount:);
  2270. [menuArray addObject:item];
  2271. }
  2272. // Add + new account
  2273. CCMenuItem *item = [[CCMenuItem alloc] init];
  2274. item.title = NSLocalizedString(@"_add_account_", nil);
  2275. item.argument = @"";
  2276. item.image = [UIImage imageNamed:@"settingsAccountNextcloud"];
  2277. item.target = self;
  2278. item.action = @selector(addNewAccount:);
  2279. [menuArray addObject:item];
  2280. OptionalConfiguration options;
  2281. Color textColor, backgroundColor;
  2282. textColor.R = 0;
  2283. textColor.G = 0;
  2284. textColor.B = 0;
  2285. backgroundColor.R = 1;
  2286. backgroundColor.G = 1;
  2287. backgroundColor.B = 1;
  2288. options.arrowSize = 9;
  2289. options.marginXSpacing = 7;
  2290. options.marginYSpacing = 10;
  2291. options.intervalSpacing = 20;
  2292. options.menuCornerRadius = 6.5;
  2293. options.maskToBackground = NO;
  2294. options.shadowOfMenu = YES;
  2295. options.hasSeperatorLine = YES;
  2296. options.seperatorLineHasInsets = YES;
  2297. options.textColor = textColor;
  2298. options.menuBackgroundColor = backgroundColor;
  2299. CGRect rect = self.view.frame;
  2300. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2301. CGFloat safeAreaTop = 0;
  2302. CGFloat offsetY = 35;
  2303. if (@available(iOS 11, *)) {
  2304. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2305. }
  2306. rect.origin.y = locationY + safeAreaTop + offsetY;
  2307. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2308. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2309. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2310. }
  2311. - (void)changeDefaultAccount:(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. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2321. if (tableAccount) {
  2322. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2323. // go to home sweet home
  2324. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2325. }
  2326. });
  2327. }
  2328. - (void)addNewAccount:(CCMenuItem *)sender
  2329. {
  2330. // Verify session in progress
  2331. if ([[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionTaskIdentifier > 0", appDelegate.activeAccount] sorted:nil ascending:NO] count] > 0) {
  2332. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2333. return;
  2334. }
  2335. [appDelegate.netQueue cancelAllOperations];
  2336. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2337. [appDelegate openLoginView:self loginType:loginAdd];
  2338. });
  2339. }
  2340. #pragma --------------------------------------------------------------------------------------------
  2341. #pragma mark ==== ReMenu ====
  2342. #pragma --------------------------------------------------------------------------------------------
  2343. - (void)createReMenuBackgroundView:(REMenu *)menu
  2344. {
  2345. CGFloat safeAreaBottom = 0;
  2346. CGFloat safeAreaTop = 0;
  2347. CGFloat statusBar = 0;
  2348. if (@available(iOS 11, *)) {
  2349. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2350. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2351. }
  2352. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2353. statusBar = 13;
  2354. }
  2355. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2356. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2357. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2358. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2359. [UIView animateWithDuration:0.2 animations:^{
  2360. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2361. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2362. if (y>minimum) {
  2363. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2364. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2365. }
  2366. }];
  2367. }
  2368. - (void)createReMainMenu
  2369. {
  2370. NSString *ordinamento;
  2371. NSString *groupBy = _directoryGroupBy;
  2372. __block NSString *nuovoOrdinamento;
  2373. NSString *titoloNuovo, *titoloAttuale;
  2374. BOOL ascendente;
  2375. __block BOOL nuovoAscendente;
  2376. UIImage *image;
  2377. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2378. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2379. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2380. [self tableViewSelect:YES];
  2381. }
  2382. }];
  2383. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2384. ordinamento = _directoryOrder;
  2385. if ([ordinamento isEqualToString:@"fileName"]) {
  2386. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brandElement];
  2387. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2388. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2389. nuovoOrdinamento = @"date";
  2390. }
  2391. if ([ordinamento isEqualToString:@"date"]) {
  2392. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brandElement];
  2393. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2394. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2395. nuovoOrdinamento = @"fileName";
  2396. }
  2397. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2398. [self orderTable:nuovoOrdinamento];
  2399. }];
  2400. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2401. ascendente = [CCUtility getAscendingSettings];
  2402. if (ascendente) {
  2403. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2404. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2405. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2406. nuovoAscendente = false;
  2407. }
  2408. if (!ascendente) {
  2409. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2410. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2411. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2412. nuovoAscendente = true;
  2413. }
  2414. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2415. [self ascendingTable:nuovoAscendente];
  2416. }];
  2417. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2418. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2419. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2420. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2421. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2422. else [self tableGroupBy:@"alphabetic"];
  2423. }];
  2424. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2425. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2426. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2427. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2428. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2429. else [self tableGroupBy:@"typefile"];
  2430. }];
  2431. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2432. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2433. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2434. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2435. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2436. else [self tableGroupBy:@"date"];
  2437. }];
  2438. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2439. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2440. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2441. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2442. if ([CCUtility getDirectoryOnTop])
  2443. [self directoryOnTop:NO];
  2444. else
  2445. [self directoryOnTop:YES];
  2446. }];
  2447. // REMENU --------------------------------------------------------------------------------------------------------------
  2448. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2449. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2450. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2451. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2452. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2453. appDelegate.reMainMenu.separatorHeight = 0.5;
  2454. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2455. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2456. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2457. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2458. appDelegate.reMainMenu.textShadowColor = nil;
  2459. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2460. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2461. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2462. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2463. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2464. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2465. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2466. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2467. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2468. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2469. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2470. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2471. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2472. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2473. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2474. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2475. appDelegate.reMainMenu.borderWidth = 0.3;
  2476. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2477. appDelegate.reMainMenu.animationDuration = 0.2;
  2478. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2479. appDelegate.reMainMenu.bounce = NO;
  2480. __weak typeof(self) weakSelf = self;
  2481. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2482. // Backgroun reMenu (Gesture)
  2483. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2484. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2485. }];
  2486. }
  2487. - (void)toggleReMainMenu
  2488. {
  2489. if (appDelegate.reMainMenu.isOpen) {
  2490. [appDelegate.reMainMenu close];
  2491. } else {
  2492. [self createReMainMenu];
  2493. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2494. // Backgroun reMenu & (Gesture)
  2495. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2496. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2497. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2498. }
  2499. }
  2500. - (void)createReSelectMenu
  2501. {
  2502. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2503. 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) {
  2504. [self deleteFile];
  2505. }];
  2506. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2507. 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) {
  2508. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2509. }];
  2510. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2511. 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) {
  2512. [self downloadSelectedFilesFolders];
  2513. }];
  2514. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2515. 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) {
  2516. [self saveSelectedFiles];
  2517. }];
  2518. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem]];
  2519. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2520. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2521. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2522. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2523. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2524. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2525. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2526. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2527. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2528. appDelegate.reSelectMenu.textShadowColor = nil;
  2529. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2530. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2531. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2532. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2533. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2534. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2535. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2536. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2537. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2538. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2539. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2540. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2541. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2542. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2543. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2544. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2545. appDelegate.reSelectMenu.borderWidth = 0.3;
  2546. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2547. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2548. appDelegate.reSelectMenu.animationDuration = 0.2;
  2549. appDelegate.reSelectMenu.bounce = NO;
  2550. __weak typeof(self) weakSelf = self;
  2551. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2552. // Backgroun reMenu (Gesture)
  2553. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2554. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2555. }];
  2556. }
  2557. - (void)toggleReSelectMenu
  2558. {
  2559. if (appDelegate.reSelectMenu.isOpen) {
  2560. [appDelegate.reSelectMenu close];
  2561. } else {
  2562. [self createReSelectMenu];
  2563. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2564. // Backgroun reMenu & (Gesture)
  2565. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2566. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2567. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2568. }
  2569. }
  2570. #pragma --------------------------------------------------------------------------------------------
  2571. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2572. #pragma --------------------------------------------------------------------------------------------
  2573. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2574. {
  2575. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2576. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2577. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2578. if ([self indexPathIsValid:indexPath])
  2579. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2580. else
  2581. _metadata = nil;
  2582. [self becomeFirstResponder];
  2583. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2584. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2585. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2586. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2587. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2588. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2589. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2590. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2591. [menuController setMenuVisible:YES animated:YES];
  2592. }
  2593. }
  2594. - (BOOL)canBecomeFirstResponder
  2595. {
  2596. return YES;
  2597. }
  2598. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2599. {
  2600. // For copy file, copy files, Open in ... :
  2601. //
  2602. // NO Directory
  2603. // NO Error Passcode
  2604. // NO In Session mode (download/upload)
  2605. // NO Template
  2606. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2607. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2608. else return NO;
  2609. }
  2610. if (@selector(copyFiles:) == action) {
  2611. if (_isSelectedMode) {
  2612. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2613. for (tableMetadata *metadata in selectedMetadatas) {
  2614. if (!metadata.directory && metadata.session.length == 0)
  2615. return YES;
  2616. }
  2617. }
  2618. return NO;
  2619. }
  2620. if (@selector(pasteFile:) == action) {
  2621. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2622. NSArray *items = [pasteboard items];
  2623. if ([items count] == 1) {
  2624. // Value : (NSData) fileID
  2625. NSDictionary *dic = [items objectAtIndex:0];
  2626. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2627. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2628. if (fileID) {
  2629. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2630. if (metadata) {
  2631. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2632. if (account) {
  2633. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2634. if (directoryUser)
  2635. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2636. return YES;
  2637. }
  2638. }
  2639. }
  2640. }
  2641. return NO;
  2642. }
  2643. if (@selector(pasteFiles:) == action) {
  2644. BOOL isValid = NO;
  2645. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2646. NSArray *items = [pasteboard items];
  2647. if ([items count] <= 1) return NO;
  2648. for (NSDictionary *dic in items) {
  2649. // Value : (NSData) fileID
  2650. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2651. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2652. if (fileID) {
  2653. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2654. if (metadata) {
  2655. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2656. if (account) {
  2657. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2658. if (directoryUser) {
  2659. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2660. isValid = YES;
  2661. } else {
  2662. isValid = NO;
  2663. break;
  2664. }
  2665. } else {
  2666. isValid = NO;
  2667. break;
  2668. }
  2669. } else {
  2670. isValid = NO;
  2671. break;
  2672. }
  2673. } else {
  2674. isValid = NO;
  2675. break;
  2676. }
  2677. } else {
  2678. isValid = NO;
  2679. break;
  2680. }
  2681. }
  2682. return isValid;
  2683. }
  2684. return NO;
  2685. }
  2686. /************************************ COPY ************************************/
  2687. - (void)copyFile:(id)sender
  2688. {
  2689. // Remove all item
  2690. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2691. pasteboard.items = [[NSArray alloc] init];
  2692. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser,_metadata.fileID]]) {
  2693. [self copyFileToPasteboard:_metadata];
  2694. } else {
  2695. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2696. if (serverUrl)
  2697. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2698. }
  2699. }
  2700. - (void)copyFiles:(id)sender
  2701. {
  2702. // Remove all item
  2703. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2704. pasteboard.items = [[NSArray alloc] init];
  2705. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2706. for (tableMetadata *metadata in selectedMetadatas) {
  2707. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]]) {
  2708. [self copyFileToPasteboard:metadata];
  2709. } else {
  2710. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2711. if (serverUrl)
  2712. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2713. }
  2714. }
  2715. [self tableViewSelect:NO];
  2716. }
  2717. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2718. {
  2719. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2720. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2721. // Value : (NSData) fileID
  2722. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2723. [items addObject:item];
  2724. [pasteboard setItems:items];
  2725. }
  2726. /************************************ OPEN IN ... ******************************/
  2727. - (void)openinFile:(id)sender
  2728. {
  2729. [self openIn:_metadata];
  2730. }
  2731. /************************************ PASTE ************************************/
  2732. - (void)pasteFile:(id)sender
  2733. {
  2734. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2735. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2736. }
  2737. - (void)pasteFiles:(id)sender
  2738. {
  2739. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2740. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2741. }
  2742. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2743. {
  2744. float timer = 0;
  2745. for (NSDictionary *dic in items) {
  2746. // Value : (NSData) fileID
  2747. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2748. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2749. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2750. if (metadata) {
  2751. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2752. if (account) {
  2753. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2754. if (directoryUser) {
  2755. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2756. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileNameView]];
  2757. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2758. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNameView serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2759. });
  2760. timer += 0.1;
  2761. }
  2762. }
  2763. }
  2764. }
  2765. }
  2766. }
  2767. #pragma --------------------------------------------------------------------------------------------
  2768. #pragma mark ===== Lock Passcode =====
  2769. #pragma --------------------------------------------------------------------------------------------
  2770. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2771. {
  2772. return _failedAttempts;
  2773. }
  2774. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2775. {
  2776. return _lockUntilDate;
  2777. }
  2778. - (void)passcodeViewCloseButtonPressed:(id)sender
  2779. {
  2780. [self dismissViewControllerAnimated:YES completion:nil];
  2781. }
  2782. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2783. {
  2784. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2785. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2786. _lockUntilDate = nil;
  2787. _failedAttempts = 0;
  2788. aResultHandler(YES);
  2789. } else aResultHandler(NO);
  2790. } else aResultHandler(YES);
  2791. }
  2792. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2793. {
  2794. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2795. switch (aViewController.type) {
  2796. case BKPasscodeViewControllerCheckPasscodeType: {
  2797. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2798. // possiamo procedere alla prossima directory
  2799. [self performSegueDirectoryWithControlPasscode:false];
  2800. // avviamo la sessione Passcode Lock con now
  2801. appDelegate.sessionePasscodeLock = [NSDate date];
  2802. }
  2803. // disattivazione lock cartella
  2804. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2805. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2806. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2807. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2808. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2809. }
  2810. [self tableViewReloadData];
  2811. }
  2812. }
  2813. break;
  2814. default:
  2815. break;
  2816. }
  2817. }
  2818. - (void)comandoLockPassword
  2819. {
  2820. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2821. if (!serverUrl) return;
  2822. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2823. // se non è abilitato il Lock Passcode esci
  2824. if ([[CCUtility getBlockCode] length] == 0) {
  2825. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2826. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2827. [alertController addAction:okAction];
  2828. [self presentViewController:alertController animated:YES completion:nil];
  2829. return;
  2830. }
  2831. // se è richiesta la disattivazione si chiede la password
  2832. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2833. if (directory.lock) {
  2834. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2835. viewController.delegate = self;
  2836. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2837. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2838. viewController.inputViewTitlePassword = YES;
  2839. if ([CCUtility getSimplyBlockCode]) {
  2840. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2841. viewController.passcodeInputView.maximumLength = 6;
  2842. } else {
  2843. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2844. viewController.passcodeInputView.maximumLength = 64;
  2845. }
  2846. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2847. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2848. viewController.touchIDManager = touchIDManager;
  2849. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2850. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2851. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2852. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2853. [self presentViewController:navigationController animated:YES completion:nil];
  2854. return;
  2855. }
  2856. // ---------------- ACTIVATE PASSWORD
  2857. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2858. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2859. if ([self indexPathIsValid:indexPath])
  2860. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2861. } else {
  2862. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2863. }
  2864. }
  2865. #pragma mark -
  2866. #pragma --------------------------------------------------------------------------------------------
  2867. #pragma mark ===== Swipe Tablet -> menu =====
  2868. #pragma --------------------------------------------------------------------------------------------
  2869. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2870. {
  2871. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2872. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2873. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2874. return NO;
  2875. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2876. return NO;
  2877. // E2EE
  2878. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount] && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2879. return NO;
  2880. return YES;
  2881. }
  2882. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2883. {
  2884. }
  2885. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2886. {
  2887. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2888. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2889. if (direction == MGSwipeDirectionRightToLeft) {
  2890. // Delete
  2891. if (index == 0)
  2892. [self swipeDelete:indexPath];
  2893. // More
  2894. if (index == 1)
  2895. [self swipeMore:indexPath];
  2896. }
  2897. if (direction == MGSwipeDirectionLeftToRight) {
  2898. if (_metadata.favorite)
  2899. [self removeFavorite:_metadata];
  2900. else
  2901. [self addFavorite:_metadata];
  2902. }
  2903. return YES;
  2904. }
  2905. - (void)swipeDelete:(NSIndexPath *)indexPath
  2906. {
  2907. // Directory locked ?
  2908. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2909. if (!lockServerUrl) return;
  2910. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2911. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2912. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2913. return;
  2914. }
  2915. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2916. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2917. [self performSelector:@selector(deleteFile) withObject:nil];
  2918. }]];
  2919. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2920. [alertController dismissViewControllerAnimated:YES completion:nil];
  2921. }]];
  2922. alertController.popoverPresentationController.sourceView = self.view;
  2923. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2924. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2925. [alertController.view layoutIfNeeded];
  2926. [self presentViewController:alertController animated:YES completion:nil];
  2927. }
  2928. - (void)swipeMore:(NSIndexPath *)indexPath
  2929. {
  2930. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2931. if (!serverUrl) return;
  2932. NSString *titoloLock, *titleFavorite;
  2933. if (_metadata.favorite) {
  2934. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2935. } else {
  2936. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2937. }
  2938. if (_metadata.directory) {
  2939. // calcolo lockServerUrl
  2940. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2941. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2942. if (directory.lock)
  2943. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2944. else
  2945. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2946. }
  2947. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2948. // ******************************************* AHKActionSheet *******************************************
  2949. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2950. actionSheet.animationDuration = 0.2;
  2951. actionSheet.buttonHeight = 50.0;
  2952. actionSheet.cancelButtonHeight = 50.0f;
  2953. actionSheet.separatorHeight = 5.0f;
  2954. actionSheet.automaticallyTintButtonImages = @(NO);
  2955. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2956. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2957. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2958. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2959. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2960. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2961. // ******************************************* DIRECTORY *******************************************
  2962. if (_metadata.directory) {
  2963. BOOL lockDirectory = NO;
  2964. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2965. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2966. // Directory bloccata ?
  2967. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, dirServerUrl]];
  2968. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2969. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2970. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement]
  2971. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2972. height:50.0
  2973. type:AHKActionSheetButtonTypeDisabled
  2974. handler:nil
  2975. ];
  2976. if (!lockDirectory && !isFolderEncrypted) {
  2977. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2978. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement]
  2979. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2980. height:50.0
  2981. type:AHKActionSheetButtonTypeDefault
  2982. handler:^(AHKActionSheet *as) {
  2983. [self openWindowShare:_metadata];
  2984. }];
  2985. }
  2986. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2987. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2988. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brandElement]
  2989. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2990. height:50.0
  2991. type:AHKActionSheetButtonTypeDefault
  2992. handler:^(AHKActionSheet *as) {
  2993. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2994. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2995. textField.text = _metadata.fileNameView;
  2996. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2997. //textField.delegate = self;
  2998. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2999. }];
  3000. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3001. NSLog(@"[LOG] Cancel action");
  3002. }];
  3003. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3004. UITextField *fileName = alertController.textFields.firstObject;
  3005. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3006. }];
  3007. okAction.enabled = NO;
  3008. [alertController addAction:cancelAction];
  3009. [alertController addAction:okAction];
  3010. [self presentViewController:alertController animated:YES completion:nil];
  3011. }];
  3012. }
  3013. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  3014. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3015. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brandElement]
  3016. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3017. height:50.0
  3018. type:AHKActionSheetButtonTypeDefault
  3019. handler:^(AHKActionSheet *as) {
  3020. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3021. }];
  3022. }
  3023. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  3024. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3025. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brandElement]
  3026. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3027. height:50.0
  3028. type:AHKActionSheetButtonTypeDefault
  3029. handler:^(AHKActionSheet *as) {
  3030. // Settings new folder Automatatic upload
  3031. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3032. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  3033. // Clear data (old) Auto Upload
  3034. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  3035. if (appDelegate.activeAccount.length > 0 && appDelegate.activePhotos)
  3036. [appDelegate.activePhotos reloadDatasourceForced];
  3037. [self readFolder:serverUrl];
  3038. NSLog(@"[LOG] Update Folder Photo");
  3039. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  3040. if ([autoUploadPath length] > 0) {
  3041. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  3042. }
  3043. }];
  3044. }
  3045. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  3046. [actionSheet addButtonWithTitle:titoloLock
  3047. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] color:[NCBrandColor sharedInstance].brandElement]
  3048. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3049. height:50.0
  3050. type:AHKActionSheetButtonTypeDefault
  3051. handler:^(AHKActionSheet *as) {
  3052. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3053. }];
  3054. }
  3055. if (!_metadata.e2eEncrypted) {
  3056. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  3057. image:[UIImage imageNamed:@"encrypted_empty"]
  3058. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3059. height:50.0
  3060. type:AHKActionSheetButtonTypeEncrypted
  3061. handler:^(AHKActionSheet *as) {
  3062. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3063. NSString *token;
  3064. NSError *error = [[NCNetworkingSync sharedManager] markEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] token:&token];
  3065. dispatch_async(dispatch_get_main_queue(), ^{
  3066. if (error) {
  3067. [appDelegate messageNotification:@"_error_e2ee_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  3068. } else {
  3069. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  3070. [self readFolder:self.serverUrl];
  3071. }
  3072. });
  3073. });
  3074. }];
  3075. }
  3076. if (_metadata.e2eEncrypted) {
  3077. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  3078. image:[UIImage imageNamed:@"encrypted_empty"]
  3079. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3080. height:50.0
  3081. type:AHKActionSheetButtonTypeEncrypted
  3082. handler:^(AHKActionSheet *as) {
  3083. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3084. NSString *token;
  3085. NSError *error = [[NCNetworkingSync sharedManager] deletemarkEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] token:&token];
  3086. dispatch_async(dispatch_get_main_queue(), ^{
  3087. if (error) {
  3088. [appDelegate messageNotification:@"_error_e2ee_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  3089. } else {
  3090. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  3091. [self readFolder:self.serverUrl];
  3092. }
  3093. });
  3094. });
  3095. }];
  3096. }
  3097. if (directory.e2eTokenLock.length > 0) {
  3098. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_lock_", nil)
  3099. image:[UIImage imageNamed:@"encrypted_empty"]
  3100. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3101. height:50.0
  3102. type:AHKActionSheetButtonTypeEncrypted
  3103. handler:^(AHKActionSheet *as) {
  3104. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3105. NSError *error = [[NCNetworkingSync sharedManager] unlockEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadata.fileID token:directory.e2eTokenLock];
  3106. if (error) {
  3107. dispatch_async(dispatch_get_main_queue(), ^{
  3108. [appDelegate messageNotification:@"_error_e2ee_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  3109. });
  3110. }
  3111. });
  3112. }];
  3113. }
  3114. [actionSheet show];
  3115. }
  3116. // ******************************************* FILE *******************************************
  3117. if (!_metadata.directory) {
  3118. UIImage *iconHeader;
  3119. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount];
  3120. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3121. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]])
  3122. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]];
  3123. else
  3124. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3125. [actionSheet addButtonWithTitle: _metadata.fileNameView
  3126. image: iconHeader
  3127. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3128. height: 50.0
  3129. type: AHKActionSheetButtonTypeDisabled
  3130. handler: nil
  3131. ];
  3132. if (!isFolderEncrypted) {
  3133. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3134. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brandElement]
  3135. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3136. height: 50.0
  3137. type:AHKActionSheetButtonTypeDefault
  3138. handler:^(AHKActionSheet *as) {
  3139. [self openWindowShare:_metadata];
  3140. }];
  3141. }
  3142. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3143. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brandElement]
  3144. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3145. height: 50.0
  3146. type:AHKActionSheetButtonTypeDefault
  3147. handler:^(AHKActionSheet *as) {
  3148. [self performSelector:@selector(openIn:) withObject:_metadata];
  3149. }];
  3150. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3151. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brandElement]
  3152. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3153. height: 50.0
  3154. type:AHKActionSheetButtonTypeDefault
  3155. handler:^(AHKActionSheet *as) {
  3156. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3157. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3158. textField.text = _metadata.fileNameView;
  3159. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3160. }];
  3161. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3162. NSLog(@"[LOG] Cancel action");
  3163. }];
  3164. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3165. UITextField *fileName = alertController.textFields.firstObject;
  3166. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3167. }];
  3168. okAction.enabled = NO;
  3169. [alertController addAction:cancelAction];
  3170. [alertController addAction:okAction];
  3171. [self presentViewController:alertController animated:YES completion:nil];
  3172. }];
  3173. if (!isFolderEncrypted) {
  3174. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3175. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brandElement]
  3176. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3177. height:50.0
  3178. type:AHKActionSheetButtonTypeDefault
  3179. handler:^(AHKActionSheet *as) {
  3180. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3181. }];
  3182. }
  3183. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3184. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3185. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brandElement]
  3186. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3187. height:50.0
  3188. type:AHKActionSheetButtonTypeDefault
  3189. handler:^(AHKActionSheet *as) {
  3190. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3191. }];
  3192. }
  3193. [actionSheet show];
  3194. }
  3195. }
  3196. #pragma --------------------------------------------------------------------------------------------
  3197. #pragma mark - ==== Datasource ====
  3198. #pragma --------------------------------------------------------------------------------------------
  3199. - (void)clearDateReadDataSource:(NSNotification *)notification
  3200. {
  3201. _dateReadDataSource = Nil;
  3202. [self reloadDatasource];
  3203. }
  3204. - (void)reloadDatasource
  3205. {
  3206. [self reloadDatasource:_serverUrl];
  3207. }
  3208. - (void)reloadDatasource:(NSString *)serverUrl
  3209. {
  3210. // test
  3211. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3212. return;
  3213. // Search Mode
  3214. if (_isSearchMode) {
  3215. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil e2eEncryptions:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3216. [self tableViewReloadData];
  3217. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3218. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3219. _noFilesSearchDescription = @"";
  3220. }
  3221. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3222. _noFilesSearchTitle = @"";
  3223. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3224. }
  3225. [self.tableView reloadEmptyDataSet];
  3226. return;
  3227. }
  3228. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3229. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3230. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  3231. if (main) {
  3232. [main reloadDatasource];
  3233. } else {
  3234. [self tableViewReloadData];
  3235. [appDelegate.activeTransfers reloadDatasource];
  3236. }
  3237. return;
  3238. }
  3239. [appDelegate.activeTransfers reloadDatasource];
  3240. // Settaggio variabili per le ottimizzazioni
  3241. _directoryGroupBy = [CCUtility getGroupBySettings];
  3242. _directoryOrder = [CCUtility getOrderSettings];
  3243. // Remove optimization for encrypted directory
  3244. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount])
  3245. _dateReadDataSource = nil;
  3246. // current directoryID
  3247. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3248. // Controllo data lettura Data Source
  3249. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3250. // Get MetadataFolder
  3251. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileID = %@", appDelegate.activeAccount, tableDirectory.fileID]];
  3252. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3253. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3254. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3255. _dateReadDataSource = [NSDate date];
  3256. // Data Source
  3257. NSString *sorted = _directoryOrder;
  3258. if ([sorted isEqualToString:@"fileName"])
  3259. sorted = @"fileName";
  3260. if (directoryID) {
  3261. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", appDelegate.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3262. NSArray *recordsTableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionsWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3263. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3264. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil e2eEncryptions:recordsTableE2eEncryption groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3265. // get auto upload folder
  3266. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3267. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3268. }
  3269. } else {
  3270. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3271. }
  3272. [self tableViewReloadData];
  3273. }
  3274. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3275. {
  3276. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3277. if (selectedRows.count > 0) {
  3278. for (NSIndexPath *selectionIndex in selectedRows) {
  3279. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3280. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3281. [metadatas addObject:metadata];
  3282. }
  3283. }
  3284. return metadatas;
  3285. }
  3286. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3287. {
  3288. NSInteger section = indexPath.section + 1;
  3289. NSInteger row = indexPath.row + 1;
  3290. NSInteger totSections = [_sectionDataSource.sections count] ;
  3291. if ((totSections < section) || (section > totSections)) {
  3292. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3293. return nil;
  3294. }
  3295. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3296. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3297. if (fileIDs) {
  3298. NSInteger totRows =[fileIDs count] ;
  3299. if ((totRows < row) || (row > totRows)) {
  3300. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3301. return nil;
  3302. }
  3303. } else {
  3304. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3305. return nil;
  3306. }
  3307. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3308. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3309. return metadata;
  3310. }
  3311. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3312. {
  3313. NSInteger totSections =[_sectionDataSource.sections count] ;
  3314. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3315. return nil;
  3316. }
  3317. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3318. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3319. }
  3320. #pragma --------------------------------------------------------------------------------------------
  3321. #pragma mark - ==== Table ====
  3322. #pragma --------------------------------------------------------------------------------------------
  3323. - (void)tableViewSelect:(BOOL)edit
  3324. {
  3325. // chiudiamo eventuali swipe aperti
  3326. if (edit)
  3327. [self.tableView setEditing:NO animated:NO];
  3328. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3329. [self.tableView setEditing:edit animated:YES];
  3330. _isSelectedMode = edit;
  3331. if (edit)
  3332. [self setUINavigationBarSelected];
  3333. else
  3334. [self setUINavigationBarDefault];
  3335. [_selectedFileIDsMetadatas removeAllObjects];
  3336. [self setTitle];
  3337. }
  3338. - (void)tableViewReloadData
  3339. {
  3340. // store selected cells before relod
  3341. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3342. //store swipeOffset before relod
  3343. [_statusSwipeCell removeAllObjects];
  3344. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3345. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3346. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3347. }
  3348. // reload table view
  3349. [self.tableView reloadData];
  3350. // selected cells stored
  3351. for (NSIndexPath *path in indexPaths)
  3352. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3353. [self setTableViewFooter];
  3354. if (self.tableView.editing)
  3355. [self setTitle];
  3356. }
  3357. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3358. {
  3359. if (tableView.editing == 1) {
  3360. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3361. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3362. return NO;
  3363. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3364. return NO;
  3365. else
  3366. return YES;
  3367. } else {
  3368. [_selectedFileIDsMetadatas removeAllObjects];
  3369. }
  3370. return YES;
  3371. }
  3372. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3373. {
  3374. return 60;
  3375. }
  3376. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3377. {
  3378. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3379. }
  3380. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3381. {
  3382. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3383. }
  3384. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3385. {
  3386. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3387. NSString *sectionTitle = [sections objectAtIndex:section];
  3388. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3389. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3390. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3391. return 20.f;
  3392. }
  3393. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3394. {
  3395. float shift;
  3396. UIVisualEffectView *visualEffectView;
  3397. NSString *titleSection;
  3398. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3399. return nil;
  3400. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3401. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3402. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3403. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3404. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3405. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3406. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3407. else titleSection = NSLocalizedString(titleSection,nil);
  3408. // Format title
  3409. NSString *currentDevice = [CCUtility currentDevice];
  3410. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3411. visualEffectView = [[UIVisualEffectView alloc] init];
  3412. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3413. } else {
  3414. UIVisualEffect *blurEffect;
  3415. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3416. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3417. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3418. }
  3419. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3420. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3421. shift = - 35;
  3422. else
  3423. shift = - 20;
  3424. } else shift = - 10;
  3425. // Title
  3426. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3427. titleLabel.backgroundColor = [UIColor clearColor];
  3428. titleLabel.textColor = [UIColor blackColor];
  3429. titleLabel.font = [UIFont systemFontOfSize:12];
  3430. titleLabel.textAlignment = NSTextAlignmentLeft;
  3431. titleLabel.text = titleSection;
  3432. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3433. [visualEffectView.contentView addSubview:titleLabel];
  3434. // Elements
  3435. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3436. elementLabel.backgroundColor = [UIColor clearColor];
  3437. elementLabel.textColor = [UIColor blackColor];;
  3438. elementLabel.font = [UIFont systemFontOfSize:12];
  3439. elementLabel.textAlignment = NSTextAlignmentRight;
  3440. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3441. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3442. NSUInteger rowsCount = [metadatas count];
  3443. if (rowsCount == 0) return nil;
  3444. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3445. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3446. [visualEffectView.contentView addSubview:elementLabel];
  3447. return visualEffectView;
  3448. }
  3449. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3450. {
  3451. return [_sectionDataSource.sections indexOfObject:title];
  3452. }
  3453. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3454. {
  3455. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3456. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3457. else
  3458. return nil;
  3459. }
  3460. /*
  3461. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3462. {
  3463. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3464. }
  3465. }
  3466. */
  3467. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3468. {
  3469. NSString *typeCell;
  3470. NSString *dataFile;
  3471. NSString *lunghezzaFile;
  3472. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3473. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3474. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3475. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3476. if (!serverUrl)
  3477. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3478. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3479. else typeCell = @"CellMainTransfer";
  3480. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3481. // variable base
  3482. cell.delegate = self;
  3483. cell.indexPath = indexPath;
  3484. // separator
  3485. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3486. // change color selection
  3487. UIView *selectionColor = [[UIView alloc] init];
  3488. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3489. cell.selectedBackgroundView = selectionColor;
  3490. // for checkmark color in editing mode
  3491. cell.tintColor = [NCBrandColor sharedInstance].brandElement;
  3492. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  3493. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3494. // ----------------------------------------------------------------------------------------------------------
  3495. // DEFAULT
  3496. // ----------------------------------------------------------------------------------------------------------
  3497. cell.file.image = nil;
  3498. cell.status.image = nil;
  3499. cell.favorite.image = nil;
  3500. cell.shared.image = nil;
  3501. cell.local.image = nil;
  3502. cell.imageTitleSegue = nil;
  3503. cell.labelTitle.enabled = YES;
  3504. cell.labelTitle.text = @"";
  3505. cell.labelInfoFile.enabled = YES;
  3506. cell.labelInfoFile.text = @"";
  3507. cell.progressView.progress = 0.0;
  3508. cell.progressView.hidden = YES;
  3509. cell.cancelTaskButton.hidden = YES;
  3510. cell.reloadTaskButton.hidden = YES;
  3511. cell.stopTaskButton.hidden = YES;
  3512. cell.labelTitle.textColor = [UIColor blackColor];
  3513. // ----------------------------------------------------------------------------------------------------------
  3514. // File Name & Folder
  3515. // ----------------------------------------------------------------------------------------------------------
  3516. // nome del file
  3517. cell.labelTitle.text = metadata.fileNameView;
  3518. // è una directory
  3519. if (metadata.directory) {
  3520. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3521. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3522. lunghezzaFile = @" ";
  3523. // ----------------------------------------------------------------------------------------------------------
  3524. // Favorite Folder
  3525. // ----------------------------------------------------------------------------------------------------------
  3526. if (metadata.favorite) {
  3527. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3528. }
  3529. } else {
  3530. // File
  3531. dataFile = [CCUtility dateDiff:metadata.date];
  3532. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3533. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3534. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3535. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3536. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3537. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]])
  3538. cell.local.image = [UIImage imageNamed:@"local"];
  3539. else
  3540. cell.local.image = nil;
  3541. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3542. cell.accessoryType = UITableViewCellAccessoryNone;
  3543. }
  3544. // ----------------------------------------------------------------------------------------------------------
  3545. // File Image View
  3546. // ----------------------------------------------------------------------------------------------------------
  3547. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3548. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  3549. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  3550. } else {
  3551. if (metadata.directory) {
  3552. if (metadata.e2eEncrypted) {
  3553. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] color:[NCBrandColor sharedInstance].brandElement];
  3554. cell.imageTitleSegue = [UIImage imageNamed:@"titleEncrypted"];
  3555. } else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory]) {
  3556. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brandElement];
  3557. cell.imageTitleSegue = [UIImage imageNamed:@"titlePhotos"];
  3558. } else
  3559. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement];
  3560. } else {
  3561. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3562. }
  3563. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO)
  3564. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3565. }
  3566. // ----------------------------------------------------------------------------------------------------------
  3567. // Image Status Lock Passcode
  3568. // ----------------------------------------------------------------------------------------------------------
  3569. // Directory con passcode lock attivato
  3570. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3571. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3572. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3573. cell.status.image = [UIImage imageNamed:@"passcode"];
  3574. // ----------------------------------------------------------------------------------------------------------
  3575. // E2EE Image Status Encrypted
  3576. // ----------------------------------------------------------------------------------------------------------
  3577. if (_metadataFolder.e2eEncrypted && !metadata.directory) {
  3578. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", appDelegate.activeAccount, metadata.fileName]];
  3579. if (tableE2eEncryption)
  3580. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3581. }
  3582. // ----------------------------------------------------------------------------------------------------------
  3583. // Favorite
  3584. // ----------------------------------------------------------------------------------------------------------
  3585. if (metadata.favorite) {
  3586. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3587. }
  3588. // ----------------------------------------------------------------------------------------------------------
  3589. // Share
  3590. // ----------------------------------------------------------------------------------------------------------
  3591. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3592. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3593. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3594. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3595. // Aggiungiamo il Tap per le shared
  3596. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3597. // Shared with you
  3598. if (isShare) {
  3599. if (metadata.directory) {
  3600. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3601. cell.imageTitleSegue = [UIImage imageNamed:@"titleShared_with_me"];
  3602. cell.accessoryType = UITableViewCellAccessoryNone;
  3603. }
  3604. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement];
  3605. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3606. [tap setNumberOfTapsRequired:1];
  3607. cell.shared.userInteractionEnabled = YES;
  3608. [cell.shared addGestureRecognizer:tap];
  3609. }
  3610. // Mounted with you
  3611. if (isMounted) {
  3612. if (metadata.directory) {
  3613. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brandElement];
  3614. cell.imageTitleSegue = [UIImage imageNamed:@"titleExternal"];
  3615. cell.accessoryType = UITableViewCellAccessoryNone;
  3616. }
  3617. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brandElement];
  3618. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3619. [tap setNumberOfTapsRequired:1];
  3620. cell.shared.userInteractionEnabled = YES;
  3621. [cell.shared addGestureRecognizer:tap];
  3622. }
  3623. // You share
  3624. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3625. if (metadata.directory) {
  3626. if ([shareUserAndGroup length] > 0) {
  3627. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3628. cell.imageTitleSegue = [UIImage imageNamed:@"titleShared_with_me"];
  3629. } if ([shareLink length] > 0) {
  3630. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brandElement];
  3631. cell.imageTitleSegue = [UIImage imageNamed:@"titlePublic"];
  3632. }
  3633. cell.shared.userInteractionEnabled = NO;
  3634. } else {
  3635. if ([shareLink length] > 0) {
  3636. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brandElement];
  3637. } if ([shareUserAndGroup length] > 0) {
  3638. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement];
  3639. }
  3640. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3641. [tap setNumberOfTapsRequired:1];
  3642. cell.shared.userInteractionEnabled = YES;
  3643. [cell.shared addGestureRecognizer:tap];
  3644. }
  3645. }
  3646. } else {
  3647. cell.shared.userInteractionEnabled = NO;
  3648. }
  3649. // ----------------------------------------------------------------------------------------------------------
  3650. // downloadFile
  3651. // ----------------------------------------------------------------------------------------------------------
  3652. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3653. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3654. // sessionTaskIdentifier : RELOAD + STOP
  3655. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3656. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3657. cell.cancelTaskButton.hidden = NO;
  3658. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3659. cell.reloadTaskButton.hidden = NO;
  3660. }
  3661. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3662. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3663. if (progress > 0) {
  3664. cell.progressView.progressTintColor = [UIColor blackColor];
  3665. cell.progressView.progress = progress;
  3666. cell.progressView.hidden = NO;
  3667. }
  3668. // ----------------------------------------------------------------------------------------------------------
  3669. // downloadFile Error
  3670. // ----------------------------------------------------------------------------------------------------------
  3671. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3672. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3673. if ([metadata.sessionError length] == 0) {
  3674. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3675. } else {
  3676. cell.labelInfoFile.text = metadata.sessionError;
  3677. }
  3678. }
  3679. }
  3680. // ----------------------------------------------------------------------------------------------------------
  3681. // uploadFile
  3682. // ----------------------------------------------------------------------------------------------------------
  3683. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3684. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3685. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3686. cell.cancelTaskButton.hidden = NO;
  3687. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3688. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3689. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3690. cell.reloadTaskButton.hidden = NO;
  3691. cell.stopTaskButton.hidden = YES;
  3692. } else {
  3693. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3694. cell.stopTaskButton.hidden = NO;
  3695. cell.reloadTaskButton.hidden = YES;
  3696. }
  3697. // se non c'è una preview in bianconero metti l'immagine di default
  3698. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]] == NO)
  3699. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brandElement];
  3700. cell.labelTitle.enabled = NO;
  3701. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3702. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3703. if (progress > 0) {
  3704. cell.progressView.progressTintColor = [UIColor blackColor];
  3705. cell.progressView.progress = progress;
  3706. cell.progressView.hidden = NO;
  3707. }
  3708. // ----------------------------------------------------------------------------------------------------------
  3709. // uploadFileError
  3710. // ----------------------------------------------------------------------------------------------------------
  3711. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3712. cell.labelTitle.enabled = NO;
  3713. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3714. if ([metadata.sessionError length] == 0) {
  3715. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3716. } else {
  3717. cell.labelInfoFile.text = metadata.sessionError;
  3718. }
  3719. }
  3720. }
  3721. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3722. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3723. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3724. // ======== MGSwipe ========
  3725. if (metadata.favorite)
  3726. 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]];
  3727. else
  3728. 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]];
  3729. cell.leftExpansion.buttonIndex = 0;
  3730. cell.leftExpansion.fillOnTrigger = NO;
  3731. //centerIconOverText
  3732. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3733. [favoriteButton centerIconOverText];
  3734. //Right
  3735. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor] padding:25]];
  3736. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3737. //centerIconOverText
  3738. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3739. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3740. [deleteButton centerIconOverText];
  3741. [moreButton centerIconOverText];
  3742. //restore swipeOffset after relod
  3743. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3744. if (swipeOffset < 0) {
  3745. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3746. [_statusSwipeCell removeObjectForKey:indexPath];
  3747. } else if (swipeOffset > 0) {
  3748. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3749. [_statusSwipeCell removeObjectForKey:indexPath];
  3750. }
  3751. return cell;
  3752. }
  3753. - (void)setTableViewFooter
  3754. {
  3755. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3756. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3757. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3758. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3759. UIFont *appFont = [UIFont systemFontOfSize:12];
  3760. footerLabel.font = appFont;
  3761. footerLabel.textColor = [UIColor grayColor];
  3762. footerLabel.backgroundColor = [UIColor clearColor];
  3763. footerLabel.textAlignment = NSTextAlignmentCenter;
  3764. NSString *folders;
  3765. NSString *files;
  3766. NSString *footerText;
  3767. if (_sectionDataSource.directories > 1) {
  3768. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3769. } else if (_sectionDataSource.directories == 1){
  3770. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3771. } else {
  3772. folders = @"";
  3773. }
  3774. if (_sectionDataSource.files > 1) {
  3775. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3776. } else if (_sectionDataSource.files == 1){
  3777. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3778. } else {
  3779. files = @"";
  3780. }
  3781. if ([folders isEqualToString:@""]) {
  3782. footerText = files;
  3783. } else if ([files isEqualToString:@""]) {
  3784. footerText = folders;
  3785. } else {
  3786. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3787. }
  3788. footerLabel.text = footerText;
  3789. [footerView addSubview:footerLabel];
  3790. [self.tableView setTableFooterView:footerView];
  3791. }
  3792. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3793. {
  3794. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3795. // settiamo il record file.
  3796. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3797. if (!_metadata)
  3798. return;
  3799. // se non può essere selezionata deseleziona
  3800. if ([cell isEditing] == NO)
  3801. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3802. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3803. if (self.tableView.editing) {
  3804. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3805. [self setTitle];
  3806. return;
  3807. }
  3808. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3809. if (!serverUrl) return;
  3810. // se è in corso una sessione
  3811. if ([_metadata.session length] > 0) return;
  3812. // file
  3813. if (_metadata.directory == NO) {
  3814. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3815. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3816. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:@"" errorMessage:@"" errorCode:0];
  3817. } else {
  3818. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount] && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3819. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3820. } else {
  3821. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3822. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3823. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3824. }
  3825. }
  3826. }
  3827. if (_metadata.directory) {
  3828. imageTitleSegue = cell.imageTitleSegue;
  3829. [self performSegueDirectoryWithControlPasscode:true];
  3830. }
  3831. }
  3832. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3833. {
  3834. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3835. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3836. [self setTitle];
  3837. }
  3838. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3839. {
  3840. if (!indexPath)
  3841. return NO;
  3842. NSInteger section = indexPath.section;
  3843. NSInteger row = indexPath.row;
  3844. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3845. if (section > lastSectionIndex || lastSectionIndex < 0)
  3846. return NO;
  3847. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3848. if (rowCount < 0)
  3849. return NO;
  3850. return row <= rowCount;
  3851. }
  3852. #pragma --------------------------------------------------------------------------------------------
  3853. #pragma mark ===== Navigation ====
  3854. #pragma --------------------------------------------------------------------------------------------
  3855. - (BOOL)shouldPerformSegue
  3856. {
  3857. // if background return
  3858. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3859. if (self.view.window == NO)
  3860. return NO;
  3861. // Collapsed ma siamo già in detail esci
  3862. if (self.splitViewController.isCollapsed)
  3863. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3864. return YES;
  3865. }
  3866. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3867. {
  3868. id viewController = segue.destinationViewController;
  3869. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3870. tableMetadata *metadata;
  3871. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3872. UINavigationController *nav = viewController;
  3873. _detailViewController = (CCDetail *)nav.topViewController;
  3874. } else {
  3875. _detailViewController = segue.destinationViewController;
  3876. }
  3877. if ([sender isKindOfClass:[tableMetadata class]]) {
  3878. metadata = sender;
  3879. [allRecordsDataSourceImagesVideos addObject:sender];
  3880. } else {
  3881. metadata = _metadata;
  3882. for (NSString *fileID in _sectionDataSource.allEtag) {
  3883. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3884. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3885. [allRecordsDataSourceImagesVideos addObject:metadata];
  3886. }
  3887. }
  3888. _detailViewController.metadataDetail = metadata;
  3889. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3890. _detailViewController.dateFilterQuery = nil;
  3891. [_detailViewController setTitle:metadata.fileNameView];
  3892. }
  3893. // can i go to next viewcontroller
  3894. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3895. {
  3896. NSString *nomeDir;
  3897. if(self.tableView.editing == NO) {
  3898. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3899. if (!serverUrl) return;
  3900. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3901. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3902. // 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
  3903. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3904. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3905. viewController.delegate = self;
  3906. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3907. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3908. viewController.inputViewTitlePassword = YES;
  3909. if ([CCUtility getSimplyBlockCode]) {
  3910. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3911. viewController.passcodeInputView.maximumLength = 6;
  3912. } else {
  3913. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3914. viewController.passcodeInputView.maximumLength = 64;
  3915. }
  3916. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3917. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3918. viewController.touchIDManager = touchIDManager;
  3919. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3920. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3921. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3922. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3923. [self presentViewController:navController animated:YES completion:nil];
  3924. return;
  3925. }
  3926. nomeDir = _metadata.fileName;
  3927. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3928. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3929. if (!viewController) {
  3930. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3931. viewController.serverUrl = serverUrlPush;
  3932. viewController.titleMain = _metadata.fileName;
  3933. viewController.textBackButton = _titleMain;
  3934. viewController.imageTitle = imageTitleSegue;
  3935. // save self
  3936. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3937. [self.navigationController pushViewController:viewController animated:YES];
  3938. } else {
  3939. if (viewController.isViewLoaded) {
  3940. // Icon Title
  3941. viewController.imageTitle = imageTitleSegue;
  3942. // Fix : Application tried to present modally an active controller
  3943. if ([self.navigationController isBeingPresented]) {
  3944. // being presented
  3945. } else if ([self.navigationController isMovingToParentViewController]) {
  3946. // being pushed
  3947. } else {
  3948. [self.navigationController pushViewController:viewController animated:YES];
  3949. }
  3950. }
  3951. }
  3952. }
  3953. }
  3954. @end