CCMain.m 238 KB

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