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